package org.jeecg.modules.zhouAdmin.admin.orderCenterModule.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.degression.mapper.MyMlccPaidanOrderGongyiMapper;
import org.jeecg.modules.degression.pojo.MlccPaidanOrderGongyi;
import org.jeecg.modules.degression.pojo.MlccPriceSystemFactoryRecord;
import org.jeecg.modules.degression.pojo.MlccPricesystemFactoryCategory;
import org.jeecg.modules.degression.pojo.MlccPricesystemFactoryRange;
import org.jeecg.modules.gwcjava.jiekou.entity.MlccUserInfo;
import org.jeecg.modules.zhouAdmin.admin.alipayrefund.RefundAlipay;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.mapper.*;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.pojo.*;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.service.IOrderCenterService;
import org.jeecg.modules.zhouAdmin.admin.util.SingleAndTeamOrderUtil;
import org.jeecg.modules.zhoupackage.mapper.*;
import org.jeecg.modules.zhoupackage.pojo.*;
import org.jeecg.modules.zhoupackage.pojo.myexcel.MyteamPriceProduct;
import org.jeecg.modules.zhoupackage.util.FabricUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@SuppressWarnings("all")
@Service
public class OrderCenterServiceImpl implements IOrderCenterService {

    @Autowired
    OrderCenterMapper mapper;

    @Autowired
    MyMlccFabricOrderinfoMapper fabricOrderinfoMapper;

    @Autowired
    MyCustomeInfoMapper customeInfoMapper;

    @Autowired
    FabricUtil fabricUtil;

    @Autowired
    MyMlccBusinessWaterInfoMapper businessWaterInfoMapper;

    @Autowired
    CartMlccUserInfoMapper userInfoMapper;

    @Autowired
    MyTrackingOrderMapper trackingOrderMapper;

    @Autowired
    MyErrorOrderMapper errorOrderMapper;

    @Autowired
    MyMlccSingleOrderInfoMapper singleOrderInfoMapper;

    @Autowired
    MyTeamOrderMapper teamOrderMapper;

    @Autowired
    MyMlccAafterSalesinfoMapper afterSalesinfoMapper;

    @Autowired
    MyMlcctrackingProductMapper trackingProductMapper;

    @Autowired
    MyMlccTrackingTeamDepartMapper trackingTeamDepartMapper;

    @Autowired
    MyMlccBatchPackingInfoMapper batchPackingInfoMapper;

    @Autowired
    MyMlccPackingSmallProductMapper packingSmallProductMapper;

    @Autowired
    TeamOrderAafterTMapper orderAafterTMapper;

    @Autowired
    MysmallProductMapper smallProductMapper;

    @Autowired
    MyMlccTrackAfterOrderMapper trackAfterOrderMapper;

    @Autowired
    MyMlccTrackafterorderPersonMapper trackafterorderPersonMapper;

    @Autowired
    MyProductBodySizeMapper productBodySizeMapper;

    @Autowired
    MlccCartInfoMapper cartInfoMapper;

    @Autowired
    MyMlccProductInfoMapper productInfoMapper;

    @Autowired
    MyMlccApplyRefundmoneyMapper refundmoneyMapper;

    @Autowired
    MyMlccTrackafterorderXpPackingMapper xpPackingMapper;

    @Autowired
    MlccFabricInfoMapper fabricInfoMapper;

    @Autowired
    SingleAndTeamOrderUtil singleUtil;

    @Autowired
    MyMlccPaidanOrderCostMapper paidanOrderCostMapper;

    @Autowired
    MyMlccPaidanOrderGongyiMapper paidanOrderGongyiMapper;

    @Autowired
    MyMlccCategoryInfoMapper categoryInfoMapper;

    @Autowired
    MyMlccSysuserOrderInfoMapper paidanMapper;

    @Autowired
    MyMlccPaidanOrderAfterMapper paidanOrderAfterMapper;

    @Autowired
    MyMlccCourierInfoMapper courierInfoMapper;

    @Autowired
    MyMlccSysuserOrderInfoMapper sysuserOrderInfoMapper;

    @Autowired
    MyMlccstoreMapper storeMapper;

    @Autowired
    MyMlccCompanyInfoMapper companyInfoMapper;

    @Autowired
    MlccOrderFabricMapper orderFabricMapper;

    @Autowired
    IOrderCenterService orderService;


    /**
     * 获取面料订单
     *
     * @return
     */
    @Override
    public IPage<AdminFabricOrder> getFabricOrder(Page<AdminFabricOrder> page, String orderSn, String storeCode,
                                                  String gysName, String status, String date, String end) {
        IPage<AdminFabricOrder> fabricOrder = mapper.getFabricOrder(page, orderSn, storeCode, gysName, status, date, end);
        if (fabricOrder.getSize() > 0) {
            for (AdminFabricOrder record : fabricOrder.getRecords()) {
                // 获取客户编号和客户名称（也就是获取门店对应的公司编号和名称）
                MlccStoreInfo storeInfo = storeMapper.selectById(record.getStoreId());
                if (storeInfo != null) {
                    MlccCompanyInfo companyInfo = companyInfoMapper.selectById(storeInfo.getCompanyId());
                    if (companyInfo != null) {
                        record.setCompanyName(companyInfo.getCompanyName()).setCompanyCode(companyInfo.getCompanyCode());
                    }
                }
                // 获取订单基本信息
                /*double mishu = 0;
                MlccFabricOrderinfo orderinfo = fabricOrderinfoMapper.selectById(record.getId());
                String[] split = orderinfo.getCartId().split(",");
                if (split.length > 0) {
                    for (String s : split) {
                        MlccCartInfo cartInfo = cartInfoMapper.selectById(s);
                        if (cartInfo != null) {
                            mishu += cartInfo.getBuyNumber();
                        }
                    }
                }
                record.setBuyNumber(mishu + "");*/
            }
        }
        return fabricOrder;
    }

    /**
     * 面料订单立即接单
     *
     * @param orderSn
     * @return
     */
    @Transactional
    @Override
    public int orderNow(String orderSn, String remark) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<MlccFabricOrderinfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccFabricOrderinfo orderinfo = fabricOrderinfoMapper.selectOne(wrapper);
        orderinfo.setStatus(3);
        int i = fabricOrderinfoMapper.updateById(orderinfo);
        if (i > 0) {
            // 订单状态跟踪表添加记录
            MlccTrackingOrder trackingOrder = new MlccTrackingOrder();
            trackingOrder.setOrderSn(orderSn).setOrderType(0).setRemark(remark).setThing("订单已接单")
                    .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname()).setOrderStatus(3);
            trackingOrderMapper.insert(trackingOrder);

            // 出库申请表添加记录
            singleUtil.addChuku(orderSn, 0);
        }
        return i;
    }

    /**
     * 个订订单立即接单
     *
     * @param orderSn 个订订单编号
     */
    @Override
    public int orderNowSingle(String orderSn) {
        // 操作人员
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 个订订单基本信息
        QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn).eq("status", 1);
        MlccSingleOrderInfo singleOrderInfo = singleOrderInfoMapper.selectOne(wrapper);
        if (singleOrderInfo == null) {
            return 0;
        }
        // 接单之前先判断，是否订单下的每个产品都已经选择了供应商
        QueryWrapper<MlccProductInfo> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("order_sn", orderSn);
        List<MlccProductInfo> productInfos = productInfoMapper.selectList(wrapper1);
        if (productInfos != null && productInfos.size() > 0) {
            for (MlccProductInfo info : productInfos) {
                // 如果任意一个产品没有选择供应商，则不能接单
                if (info.getGysId() == null || "".equals(info.getGysId())) {
                    return -1;
                }
            }
        }

        // 改为接单状态
        singleOrderInfo.setStatus(3).setUpdateBy(user.getRealname());
        int i = singleOrderInfoMapper.updateById(singleOrderInfo);
        if (i > 0) {

            // 订单状态跟踪表添加记录
            MlccTrackingOrder trackingOrder = new MlccTrackingOrder();
            trackingOrder.setOrderSn(orderSn).setOrderType(1).setThing("订单已接单")
                    .setRemark("平台已接单").setId(UUID.randomUUID().toString())
                    .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname()).setOrderStatus(3);
            trackingOrderMapper.insert(trackingOrder);

            // 如果接单成功，向派单表添加成本记录
            for (MlccProductInfo info : productInfos) {
                // 向供应商接单表添加接单记录
                int addPaidan = addPaidan(info, orderSn);
                if (addPaidan < 1) {
                    return 0;
                }
                // 往派单成本表添加记录
                int saveChengben = savePaidanChengbenNew(orderSn, info, info.getGysId());
                if (saveChengben < 1) {
                    return 0;
                }
                // 往派单工艺表添加记录
                int saveGYCB = savePaidanGYNew(orderSn, info, info.getGysId());
                if (saveGYCB < 1) {
                    return 0;
                }
            }
            // 出库申请表添加记录
            singleUtil.addChuku(orderSn, 1);
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 面料确认收货
     *
     * @param orderSn 订单编号
     * @return 结果 int
     */
    @Override
    public int theGoods(String orderSn) {
        QueryWrapper<MlccFabricOrderinfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccFabricOrderinfo orderinfo = fabricOrderinfoMapper.selectOne(wrapper);
        orderinfo.setStatus(5);
        return fabricOrderinfoMapper.updateById(orderinfo);
    }
/********************************分割线下方是个订************************************/

    /**
     * 获取个订订单
     *
     * @return
     */
    @Override
    public IPage<AdminSingleOrder> getSingleOrder(Page<AdminSingleOrder> page, String orderSn, String storeCode,
                                                  String gysName, String status, String date, String enddate) {
        IPage<AdminSingleOrder> singleOrder = mapper.getSingleOrder(page, orderSn, storeCode, gysName, status, date, enddate);
        List<AdminSingleOrder> records = singleOrder.getRecords();
        if (records != null && records.size() > 0) {
            for (AdminSingleOrder record : records) {

                // 获取客户编号和客户名称（也就是获取门店对应的公司编号和名称）
                QueryWrapper<MlccStoreInfo> wrapper = new QueryWrapper<>();
                wrapper.eq("store_code", record.getStoreId());// 你没有看错，数据库里保存的就是编号
                MlccStoreInfo storeInfo = storeMapper.selectOne(wrapper);
                if (storeInfo != null) {
                    MlccCompanyInfo companyInfo = companyInfoMapper.selectById(storeInfo.getCompanyId());
                    if (companyInfo != null) {
                        record.setCompanyName(companyInfo.getCompanyName()).setCompanyCode(companyInfo.getCompanyCode());
                    }
                }
                /*QueryWrapper<MlccProductInfo> wrapper = new QueryWrapper<>();
                wrapper.eq("order_sn", record.getOrderSn());
                List<MlccProductInfo> productInfos = productInfoMapper.selectList(wrapper);
                int num = 0;
                if (productInfos != null && productInfos.size() > 0) {
                    for (MlccProductInfo productInfo : productInfos) {
                        num += productInfo.getNumbers();
                    }
                }
                record.setNum(num + "");*/
            }
        }
        return singleOrder;
    }
/********************************分割线下方是团订************************************/

    /**
     * 获取团订订单
     *
     * @param page      分页器
     * @param orderSn   订单编号
     * @param storeName 门店名称
     * @param status    订单状态
     * @param date      下单时间
     * @return 分页数据
     */
    @Override
    public IPage<AdminTeamOrder> getTeamOrder(Page<AdminTeamOrder> page, String orderSn, String storeName,
                                              String status, String date, String enddate) {
        IPage<AdminTeamOrder> iPage = mapper.getTeamOrder(page, orderSn, storeName, status, date, enddate);
        List<AdminTeamOrder> records = iPage.getRecords();
        if (records != null && records.size() > 0) {
            for (AdminTeamOrder record : records) {
                // 获取客户编号和客户名称（也就是获取门店对应的公司编号和名称）
                MlccStoreInfo storeInfo = storeMapper.selectById(record.getStoreId());
                if (storeInfo != null) {
                    MlccCompanyInfo companyInfo = companyInfoMapper.selectById(storeInfo.getCompanyId());
                    if (companyInfo != null) {
                        record.setCompanyName(companyInfo.getCompanyName()).setCompanyCode(companyInfo.getCompanyCode());
                    }
                }
                /*if (record.getCustomerId() != null) {
                    String customerId = record.getCustomerId();
                    String departId = customeInfoMapper.selectById(customerId).getDepartId();
                    QueryWrapper<MlccCustomerInfo> wrapper = new QueryWrapper<>();
                    wrapper.eq("depart_id", departId).eq("is_company", 0);
                    Integer customeNum = customeInfoMapper.selectCount(wrapper);
                    record.setCustomeNum(customeNum);
                }*/
            }
        }
        return iPage;
    }

    /**
     * 获取个订订单详情
     *
     * @param orderSn
     */
    @Override
    public MlccSingleOrderInfo getDingleOrderDetail(String orderSn) {
        return fabricUtil.getSingleOrderDetailById3(orderSn);
    }

    /**
     * 未支付订单的调价
     *
     * @param orderType 订单类型 3面料，0个订，1团订
     * @param orderSn   订单编号
     * @param price     设置的价格
     * @return
     */
    @Override
    @Transactional
    public int pricing(Integer orderType, String orderSn, String price, String remark) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MlccTrackingOrder trackingOrder = new MlccTrackingOrder(); // 用于之后的订单跟踪
        if (orderType == 3) {
            // 面料订单改价
            return fabricPricing(user, trackingOrder, orderSn, price, remark);
        } else if (orderType == 0) {
            // 个订订单改价
            return singleOrderPricing(user, trackingOrder, orderSn, price, remark);
        } else if (orderType == 1) {
            // 团订订单改价
            return teamOrderPricing(user, trackingOrder, orderSn, price, remark);
        } else {
            return 0; // 订单类型不存在
        }
    }

    /**
     * 获取异常订单列表
     *
     * @param page
     * @param orderSn
     * @param status
     * @param date
     */
    @Override
    public IPage<MlccErrorOrder> listExceptionOrder(Page<MlccErrorOrder> page, String orderSn, String status, String date, String enddate) {
        QueryWrapper<MlccErrorOrder> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        if (orderSn != null && !"".equals(orderSn)) {
            wrapper.like("order_sn", orderSn);
        }
        if (status != null && !"".equals(status)) {
            wrapper.like("error_name", status);
        }
        if (date != null && !"".equals(date)) {
            wrapper.ge("create_time", date);
        }
        if (enddate != null && !"".equals(enddate)) {
            enddate = enddate + " 23:59:59";
            wrapper.le("create_time", enddate);
        }
        return errorOrderMapper.selectPage(page, wrapper);
    }

    /**
     * 订单跟踪状态
     *
     * @param orderSn
     * @return
     */
    @Override
    public List<MlccTrackingOrder> getFabricOrderTracking(String orderSn, Integer orderType) {
        QueryWrapper<MlccTrackingOrder> wrapper = new QueryWrapper<>();
        if (orderType == 3) { // 查询面料订单状态
            wrapper.eq("order_sn", orderSn).eq("order_type", 0).orderByDesc("create_time");
            return trackingOrderMapper.selectList(wrapper);
        } else if (orderType == 0) { //个订订单状态跟踪
            wrapper.eq("order_sn", orderSn).eq("order_type", 1).orderByDesc("create_time");
            return trackingOrderMapper.selectList(wrapper);
        } else if (orderType == 1) { // 团订
            wrapper.eq("order_sn", orderSn).eq("order_type", 2).orderByDesc("create_time");
            return trackingOrderMapper.selectList(wrapper);
        }
        return null;
    }

    /**
     * 订单售后记录跟踪
     *
     * @param token     令牌
     * @param orderSn   订单编号
     * @param orderType 订单类型
     * @return 售后记录列表
     */
    @Override
    public IPage<MlccAfterSalesinfo> listTeamAfter(Page<MlccAfterSalesinfo> page, String token, String orderSn, Integer orderType) {
        QueryWrapper<MlccAfterSalesinfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn).eq("status", 0).orderByDesc("create_time");
        if (orderType == 3) { // 如果是面料订单
            wrapper.eq("ordertype", 0);
        } else if (orderType == 0) { // 如果是个订
            wrapper.eq("ordertype", 1);
        } else if (orderType == 1) { // 如果是团订
            wrapper.eq("ordertype", 2);
        }
        return afterSalesinfoMapper.selectPage(page, wrapper);
    }

    /**
     * 个订取产品状态跟踪列表
     *
     * @param orderSn 订单编号
     */
    @Override
    public List<MlccTrackingProduct> listtrackingProduct(String orderSn) {
        // 个订查询产品状态跟踪
        /*QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccSingleOrderInfo orderInfo = singleOrderInfoMapper.selectOne(wrapper);
        String[] chanpingIds = orderInfo.getChanpingIds().split(",");
        List<String> idlist = Arrays.asList(chanpingIds);// 拿到了所有的产品ID
        if (idlist != null && idlist.size() > 0) {
            QueryWrapper<MlccTrackingProduct> wrapper1 = new QueryWrapper<>();
            wrapper1.in("product_id", idlist).ne("status", 4);
            return trackingProductMapper.selectList(wrapper1);
        } else {
            return null;
        }*/
        QueryWrapper<MlccTrackingProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn).ne("status", "4").orderByDesc("create_time");
        List<MlccTrackingProduct> trackingProducts = trackingProductMapper.selectList(wrapper);
        if (trackingProducts != null && trackingProducts.size() > 0) {
            for (MlccTrackingProduct track : trackingProducts) {
                MlccProductInfo productInfo = productInfoMapper.selectById(track.getProductId());
                if (productInfo != null) {
                    track.setProductName(productInfo.getProductName());
                }
            }
        }
        return trackingProducts;
    }

    /**
     * 团订查询部门下人员
     *
     * @param orderSn
     */
    @Override
    public JSONObject listDepartSmallPro(String orderSn) {
        QueryWrapper<MlccCustomerProductInfo> wrapper = new QueryWrapper<>();

        return null;
    }

    /**
     * 后台订单驳回
     *
     * @param orderType 订单类型
     * @param orderID   订单ID
     * @param remark    备注信息
     */
    @Override
    public int rejectedOrder(Integer orderType, String orderID, String remark) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (orderType == 3) {
            // 驳回面料订单
            MlccFabricOrderinfo orderinfo = fabricOrderinfoMapper.selectById(orderID);
            orderinfo.setStatus(9);
            int result = fabricOrderinfoMapper.updateById(orderinfo);
            if (result > 0) {
                // 订单跟踪表添加数据
                addtrackingOrder(orderinfo.getOrderSn(), 0, remark, user.getUsername(), 7, "平台驳回");
                if (orderinfo.getApplyType() == 0) {
                    // 支付宝退款
                    RefundAlipay refundAlipay = new RefundAlipay();
                    refundAlipay.refundAll(orderinfo.getOrderSn(), orderinfo.getOrderMoney(), remark);
                } else if (orderinfo.getApplyType() == 3) {
                    // 平台支付退款
                    bohuiMoneyBack(orderinfo.getId().toString(), 0, orderinfo.getUserId());
                } else if (orderinfo.getApplyType() == 1) {
                    // 微信支付退款
                }
                return result;
            } else {
                return 0;
            }
        } else if (orderType == 0) {
            // 驳回个订
            MlccSingleOrderInfo orderInfo = singleOrderInfoMapper.selectById(orderID);
            orderInfo.setStatus(10).setRefusedReason(remark);
            int result = singleOrderInfoMapper.updateById(orderInfo);
            if (result > 0) {
                // 订单跟踪表添加数据
                addtrackingOrder(orderInfo.getOrderSn(), 1, remark, user.getUsername(), 7, "订单驳回");
                if (orderInfo.getApplyType() == 0) {
                    // 支付宝退款
                    RefundAlipay refundAlipay = new RefundAlipay();
                    refundAlipay.refundAll(orderInfo.getOrderSn(), orderInfo.getOrderMoney(), remark);
                } else if (orderInfo.getApplyType() == 3) {
                    // 平台支付退款
                    bohuiMoneyBack(orderInfo.getId().toString(), 1, orderInfo.getUserId());
                } else if (orderInfo.getApplyType() == 1) {
                    // 微信支付退款
                }
                return result;
            } else {
                return 0;
            }
        } else if (orderType == 1) {
            // 驳回团订
            MlccTeamOrderInfo teamOrderInfo = teamOrderMapper.selectById(orderID);
            teamOrderInfo.setStatus(10).setRefusedReason(remark);
            int result = teamOrderMapper.updateById(teamOrderInfo);
            if (result > 0) {
                // 订单跟踪表添加数据
                // 0未支付，1已支付，2申请售后，3已接单，4已发货，5已完成，6备库 7驳回
                addtrackingOrder(teamOrderInfo.getOrderSn(), 2, remark, user.getUsername(), 7, "订单驳回");

                if (teamOrderInfo.getApplyType() == 0) {
                    // 支付宝退款
                    RefundAlipay refundAlipay = new RefundAlipay();
                    refundAlipay.refundAll(teamOrderInfo.getOrderSn(), teamOrderInfo.getOrderMoney(), remark);
                } else if (teamOrderInfo.getApplyType() == 3) {
                    // 平台支付退款
                    bohuiMoneyBack(teamOrderInfo.getId().toString(), 2, teamOrderInfo.getUserId());
                } else if (teamOrderInfo.getApplyType() == 1) {
                    // 微信支付退款
                }
                return result;
            } else {
                return 0;
            }
        } else { // 订单类型错误
            return 0;
        }
    }

    /**
     * 面料订单立即发货
     *
     * @param orderSn   订单编号
     * @param yunNumber 运单号
     * @param orderType 订单类型
     */
    @Override
    public int fahuoNow(String orderSn, String yunNumber, Integer orderType, String kuaidiid, String remark, String[] productid) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MlccCourierInfo mlccCourierInfo = courierInfoMapper.selectById(kuaidiid);
        if (orderType == 3) {
            // 面料订单立即发货
            QueryWrapper<MlccFabricOrderinfo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_sn", orderSn);
            MlccFabricOrderinfo orderinfo = fabricOrderinfoMapper.selectOne(wrapper);
            orderinfo.setStatus(4).setLogisticsSn(yunNumber).setUpdateBy(user.getRealname())
                    .setCourierId(kuaidiid).setCourierName(mlccCourierInfo.getCourierName());
            int update = fabricOrderinfoMapper.updateById(orderinfo);

            // 向订单跟踪表添加记录
            MlccTrackingOrder trackingOrder = new MlccTrackingOrder();
            trackingOrder.setOrderSn(orderSn).setOrderType(0).setRemark(remark).setLogisticsSn(yunNumber)
                    .setThing("订单发货")
                    .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname()).setOrderStatus(4);
            trackingOrderMapper.insert(trackingOrder);
            /*addtrackingOrder(orderSn, 0, "订单发货", user.getRealname(), 4);*/
            return update;
        } else if (orderType == 1) {
            // 个订订单立即发货
            QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_sn", orderSn);
            MlccSingleOrderInfo orderInfo = singleOrderInfoMapper.selectOne(wrapper);
            if (orderInfo != null) {
                orderInfo.setStatus(7).setThirdSn(yunNumber).setUpdateBy(user.getRealname());
                int i = singleOrderInfoMapper.updateById(orderInfo);
                if (i > 0) {
                    // 向订单跟踪表添加记录
                    MlccTrackingOrder trackingOrder = new MlccTrackingOrder();
                    trackingOrder.setOrderSn(orderSn).setOrderType(1).setRemark(remark).setLogisticsSn(yunNumber)
                            .setThing("订单发货")
                            .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname()).setOrderStatus(4);
                    trackingOrderMapper.insert(trackingOrder);
                    if (productid != null) {
                        for (String id : productid) {
                            // 把这个产品改成发货状态
                            MlccProductInfo info = productInfoMapper.selectById(id);
                            info.setIsOut(1);
                            productInfoMapper.updateById(info);
                            // 向产品状态跟踪表添加记录
                            MlccTrackingProduct trackingProduct = new MlccTrackingProduct();
                            trackingProduct.setId(UUID.randomUUID().toString()).setProductId(id).setStatus(5)
                                    .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname())
                                    .setSysOrgCode(user.getOrgCode()).setKdid(kuaidiid)
                                    .setYunnumber(yunNumber)
                                    .setOrderSn(orderSn).setStatusName("产品发货").setRemark(remark);
                            trackingProductMapper.insert(trackingProduct);
                        }
                    }
                }
                return i;
            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }

    /**
     * 完成订单
     *
     * @param orderSn   订单编号
     * @param orderType 订单类型 3:面料订单，0个订，1团订
     */
    @Override
    public int finishOrder(String orderSn, Integer orderType) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (orderType == 3) {
            // 面料订单完成订单
            QueryWrapper<MlccFabricOrderinfo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_sn", orderSn);
            MlccFabricOrderinfo orderinfo = fabricOrderinfoMapper.selectOne(wrapper);
            orderinfo.setStatus(5).setUpdateBy(user.getRealname());
            int update = fabricOrderinfoMapper.updateById(orderinfo);
            addtrackingOrder(orderSn, 0, "订单完成", user.getRealname(), 5, "订单完成");
            return update;
        }
        return 0;
    }

    /**
     * 订单备库
     *
     * @param orderSn   订单编号
     * @param orderType 订单类型
     * @param remark    备注信息
     */
    @Override
    public int beikuOrder(String orderSn, Integer orderType, String remark) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (orderType == 3) {
            // 面料订单备库
            QueryWrapper<MlccFabricOrderinfo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_sn", orderSn);
            MlccFabricOrderinfo orderinfo = fabricOrderinfoMapper.selectOne(wrapper);
            orderinfo.setStatus(10).setUpdateBy(user.getRealname());
            int updateById = fabricOrderinfoMapper.updateById(orderinfo);
            if (updateById > 0) {
                // 如果备库成功，需要向订单跟踪表添加一条记录
                // 0未支付，1已支付，2申请售后，3已接单，4已发货，5已完成，6备库
                addtrackingOrder(orderSn, 0, remark, user.getRealname(), 6, "订单备库");
            }
            return updateById;
        }
        return 0;
    }

    /**
     * 团订订单批次列表
     *
     * @param orderSn 订单编号
     */
    @Override
    public List<TeamPackingEntity> listPacking(String orderSn) {
        List<TeamPackingEntity> packingEntities = mapper.listPacking(orderSn);
        // 查询装箱单数量
        if (packingEntities != null && packingEntities.size() > 0) {
            for (TeamPackingEntity packingEntity : packingEntities) {
                QueryWrapper<MlccBatchPackingInfo> wrapper = new QueryWrapper<>();
                wrapper.eq("batch_id", packingEntity.getId());
                int count = batchPackingInfoMapper.selectCount(wrapper);
                packingEntity.setBoxnum(count + "");
            }
        }
        return packingEntities;
    }

    /**
     * 批次的立即发货
     *
     * @param packingID 批次ID
     * @param thirdSn   运单号
     * @param kdid      快递id
     * @param remark    发货的备注
     */
    @Override
    public int pixifahuoNow(String packingID, String thirdSn, String kdid, String remark) {
        // 查询快递信息
        MlccCourierInfo mlccCourierInfo = courierInfoMapper.selectById(kdid);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MlccTrackingTeamDepart info = trackingTeamDepartMapper.selectById(packingID);
        info.setStatus(1).setThirdSn(thirdSn).setUpdateBy(user.getRealname())
                .setCid(kdid).setCremark(remark);
        if (mlccCourierInfo != null) {
            info.setCname(mlccCourierInfo.getCourierName());
        }
        return trackingTeamDepartMapper.updateById(info);
    }

    /**
     * 删除批次
     *
     * @param packingID 批次ID
     */
    @Override
    public int delPacking(String packingID) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MlccTrackingTeamDepart info = trackingTeamDepartMapper.selectById(packingID);
        info.setStatus(-1).setUpdateBy(user.getRealname());
        return trackingTeamDepartMapper.updateById(info);
    }

    /**
     * 获取批次基本信息（详情）
     *
     * @param packingID 批次ID
     */
    @Override
    public TeamPackingEntity basePackingDetail(String packingID) {
        return mapper.basePackingDetail(packingID);
    }

    /**
     * 获取批次下的装箱单列表和装箱单下的人员列表
     *
     * @param packingID 批次ID
     */
    @Override
    public List<MlccBatchPackingInfo> listPackage(String packingID) {
        QueryWrapper<MlccBatchPackingInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("batch_id", packingID).orderByDesc("create_time");
        List<MlccBatchPackingInfo> batchPackingInfos = batchPackingInfoMapper.selectList(wrapper);
        // 查询装箱单下的人员
        for (MlccBatchPackingInfo packingInfo : batchPackingInfos) {
            packingInfo.setListPerson(mapper.listBoxPerson(packingInfo.getId()));
        }
        return batchPackingInfos;
    }

    /**
     * 导出装箱单人员列表
     *
     * @param id 装箱单id
     */
    @Override
    public List<BoxPersonEntity> getboxPersonFile(String id) {
        return mapper.listBoxPerson(id);
    }

    /**
     * 获取装箱单下的人员列表
     *
     * @param id 装箱单id
     */
    @Override
    public List<BoxPersonEntity> listBoxPerson(String id) {
        return mapper.listBoxPerson(id);
    }

    /**
     * 删除装箱单下的产品（删除关系表）
     *
     * @param id 装箱单产品关联表ID
     */
    @Override
    public int delBoxPro(String id) {
        return packingSmallProductMapper.deleteById(id);
    }

    /**
     * 新增批次
     *
     * @param departID    部门ID
     * @param packingName 批次名称
     * @param orderSn     订单编号
     */
    @Override
    public int savePacking(String departID, String packingName, String orderSn) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 同一个订单下面的两个批次名称不能重复
        QueryWrapper<MlccTrackingTeamDepart> wrapper = new QueryWrapper<>();
        wrapper.eq("team_order_sn", orderSn).eq("batch_name", packingName);
        int count = trackingTeamDepartMapper.selectCount(wrapper);
        if (count == 0) {
            MlccTrackingTeamDepart depart = new MlccTrackingTeamDepart();
            depart.setId(UUID.randomUUID().toString()).setBatchName(packingName).setTeamOrderSn(orderSn)
                    .setDepartId(departID).setStatus(0).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname())
                    .setSysOrgCode(user.getOrgCode());
            return trackingTeamDepartMapper.insert(depart);
        } else {
            return -2;
        }
    }

    /**
     * 团订未发货人员名单
     *
     * @param orderSn 订单编号
     * @return 小产品列表
     */
    @Override
    public IPage<MyNotshipmentsEmp> listNotshipments(Page<MyNotshipmentsEmp> page, String orderSn, String productID) {
        return orderAafterTMapper.listNotshipments2(page, orderSn, productID);
    }

    /**
     * 团订新增装箱单界面，根据批次ID查询产品列表
     *
     * @param batchID 批次ID
     */
    @Override
    public List<MlccProductInfo> getProductByBatchID(String batchID) {
        return mapper.getProductByBatchID(batchID);
    }

    /**
     * 团订新增装箱单，并往装箱单产品关联表添加记录
     *
     * @param batchID     批次ID
     * @param packingName 装箱单名称
     * @param remark      备注
     * @param productID   选中的小产品ID列表
     */
    @Override
    @Transactional
    public int saveBox(String batchID, String packingName, String remark, String[] productID) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MlccBatchPackingInfo batchPackingInfo = new MlccBatchPackingInfo();
        batchPackingInfo.setId(UUID.randomUUID().toString().substring(0, 12)).setCode(UUID.randomUUID().toString().substring(0, 12))
                .setBatchId(batchID).setPackingName(packingName).setRemark(remark).setCreateBy(user.getRealname())
                .setUpdateBy(user.getRealname()).setSysOrgCode(user.getOrgCode());
        int insert = batchPackingInfoMapper.insert(batchPackingInfo);
        if (insert > 0) {
            // 创建装箱单成功，往装箱单添加小产品
            if (productID != null && productID.length > 0) {
                for (String smallProductId : productID) {
                    MlccPackingSmallProduct smallProduct = new MlccPackingSmallProduct();
                    smallProduct.setPackingId(batchPackingInfo.getId()).setSmallProductId(smallProductId).setCreateBy(user.getRealname())
                            .setUpdateBy(user.getRealname()).setSysOrgCode(user.getOrgCode());
                    int insert1 = packingSmallProductMapper.insert(smallProduct);
                    if (insert1 < 1) {
                        return 0;
                    }
                }
            }
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 根据装箱单ID获取基本信息
     *
     * @param packageID 装箱单ID
     */
    @Override
    public MlccBatchPackingInfo getBasePackageDEtail(String packageID) {
        return batchPackingInfoMapper.selectById(packageID);
    }

    /**
     * 仅仅往装箱单下添加人员
     *
     * @param packageID 装箱单ID
     * @param productID 产品人员ID数组
     */
    @Override
    @Transactional
    public int addPersononPackage(String packageID, String[] productID) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (productID != null && productID.length > 0) {
            for (String proID : productID) {
                MlccPackingSmallProduct smallProduct = new MlccPackingSmallProduct();
                smallProduct.setPackingId(packageID).setSmallProductId(proID).setCreateBy(user.getRealname())
                        .setUpdateBy(user.getRealname()).setSysOrgCode(user.getOrgCode());
                int insert = packingSmallProductMapper.insert(smallProduct);
                if (insert < 1) {
                    return 0;
                }
            }
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 查询本次售后的小产品
     *
     * @param pageNo    当前页
     * @param pageSize  页面大小
     * @param afterCode 售后订单编号
     */
    @Override
    public IPage<MyAfterProduct> getAftersmallProduct(Page<MyAfterProduct> page, String afterCode) {

        return mapper.getAfterSmallPro(page, afterCode);
    }

    /**
     * 售后产品人员列表同意或拒绝
     *
     * @param afterOrderID 售后订单表ID
     * @param afterCode    售后订单编号
     * @param isAgree      是否同意 0 拒接，1同意
     * @param smallProIDS  选中的小产品id数组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int agreeAfter(String afterOrderID, String remark, String afterCode, Integer isAgree, String[] smallProIDS) {
        if (smallProIDS != null && smallProIDS.length > 0) {
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            // 售后订单表记录
            MlccAfterSalesinfo mlccAfterSalesinfo = afterSalesinfoMapper.selectById(afterOrderID);
            // 往售后订单跟踪表添加一条记录
            MlccTrackAfterOrder trackAfterOrder = new MlccTrackAfterOrder();
            trackAfterOrder.setId(UUID.randomUUID().toString().substring(0, 15)).setAfterOrderId(afterOrderID)
                    .setTrackCode(UUID.randomUUID().toString().substring(0, 15)).setType(2).setReason(remark)
                    .setAfterSalesType(mlccAfterSalesinfo.getAfterSalesType()).setStatus(isAgree == 0 ? 1 : 2)
                    .setRemark(remark).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname()).setSysOrgCode(user.getOrgCode());
            int insert = trackAfterOrderMapper.insert(trackAfterOrder);

            if (insert < 1) {
                new RuntimeException("插入订单售后跟踪表失败了。。。");
                return 0;
            }
            // 开始遍历前端传过来的小产品ID数组，往小产品售后表插入数据
            for (String smallProID : smallProIDS) {
                MlccTrackafterorderPerson trackafterorderPerson = new MlccTrackafterorderPerson();
                trackafterorderPerson.setTrackAfterOrderId(trackAfterOrder.getId()).setSmallProductId(smallProID)
                        .setType(isAgree).setAfterSn(afterCode).setStatus(0).setRemark(remark).setCreateBy(user.getRealname())
                        .setUpdateBy(user.getRealname()).setSysOrgCode(user.getOrgCode());
                int result = trackafterorderPersonMapper.insert(trackafterorderPerson);
                if (result < 1) {
                    new RuntimeException("插入小产品售后表失败了");
                    return 0;
                }
                // 哦，对了，还要改变小产品表的一个字段 (是否同意)
                MlccCustomerProductInfo customerProductInfo = smallProductMapper.selectById(smallProID);
                customerProductInfo.setAfterAgree(isAgree == 0 ? 2 : 1).setUpdateBy(user.getRealname()).setUpdateBy(user.getRealname())
                        .setSysOrgCode(user.getOrgCode());
                smallProductMapper.updateById(customerProductInfo);
                // 如果驳回了售后，将这个小产品的返修成本项删除
                if (isAgree == 0) {
                    // 驳回了之后删除之前的返修成本
                    QueryWrapper<MlccPaidanOrderAfter> wrapper = new QueryWrapper<>();
                    wrapper.eq("small_procode", customerProductInfo.getCode());
                    List<MlccPaidanOrderAfter> list = paidanOrderAfterMapper.selectList(wrapper);
                    if (list != null && list.size() > 0) {
                        // 遍历删除每一个驳回的小产品返修成本
                        for (MlccPaidanOrderAfter after : list) {
                            paidanOrderAfterMapper.deleteById(after.getId());
                        }
                    }
                } else if (isAgree == 1) {
                    // 如果是同意售后，启用返修参数
                    orderService.takeonFanxiuChengben(mlccAfterSalesinfo.getOrderSn(), mlccAfterSalesinfo.getAfterCode());
                }
            }

            // 如果驳回了售后，需要退钱！
            if (isAgree == 0) {
                rejectedAfter(mlccAfterSalesinfo.getId().toString(), mlccAfterSalesinfo.getUserId());
                // 将售后订单改为驳回状态
                mlccAfterSalesinfo.setAfterstatus(1);
                afterSalesinfoMapper.updateById(mlccAfterSalesinfo);
            }

            // 如果是同意 再向订单售后跟踪表插入一条状态为4（准备发货的数据）
            if (isAgree == 1) {
                MlccTrackAfterOrder zunbeiFahuo = new MlccTrackAfterOrder();
                zunbeiFahuo.setId(UUID.randomUUID().toString().substring(0, 15)).setAfterOrderId(afterOrderID)
                        .setTrackCode(UUID.randomUUID().toString().substring(0, 15)).setType(2).setReason(remark)
                        .setAfterSalesType(mlccAfterSalesinfo.getAfterSalesType()).setStatus(4)
                        .setRemark(remark).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname()).setSysOrgCode(user.getOrgCode());
                int insert2 = trackAfterOrderMapper.insert(zunbeiFahuo);

                // 再向售后小产品表添加记录，指向这条同意的售后跟踪记录
                // 开始遍历前端传过来的小产品ID数组，往小产品售后表插入数据
                for (String smallProID : smallProIDS) {
                    MlccTrackafterorderPerson agreePerson = new MlccTrackafterorderPerson();
                    agreePerson.setTrackAfterOrderId(zunbeiFahuo.getId()).setSmallProductId(smallProID)
                            .setType(1).setAfterSn(afterCode).setStatus(1).setRemark(remark).setCreateBy(user.getRealname())
                            .setUpdateBy(user.getRealname()).setSysOrgCode(user.getOrgCode());
                    int resultAgreePerson = trackafterorderPersonMapper.insert(agreePerson);
                    if (resultAgreePerson < 1) {
                        new RuntimeException("插入小产品售后表失败了");
                        return 0;
                    }
                }
            }
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 团订售后详情查询以及拒绝的人员
     *
     * @param afterOrderID
     */
    @Override
    public List<MlccTrackAfterOrder> listRefustProduct(String afterOrderID) {
        QueryWrapper<MlccTrackAfterOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("after_order_id", afterOrderID).eq("status", 1);

        List<MlccTrackAfterOrder> afterOrderslist = trackAfterOrderMapper.selectList(wrapper);
        for (MlccTrackAfterOrder afterOrder : afterOrderslist) {
            // 往订单售后跟踪表中添加拒绝的小产品
            afterOrder.setAfterProductList(mapper.listRefust(afterOrder.getId()));
        }
        return afterOrderslist;
    }

    /**
     * 团订售后已同意的小产品
     *
     * @param afterOrderID 售后订单ID
     */
    @Override
    public List<MlccTrackAfterOrder> listAgreeProduct(String afterOrderID) {
        QueryWrapper<MlccTrackAfterOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("after_order_id", afterOrderID).eq("status", 2);

        List<MlccTrackAfterOrder> afterOrderslist = trackAfterOrderMapper.selectList(wrapper);
        for (MlccTrackAfterOrder afterOrder : afterOrderslist) {
            // 往订单售后跟踪表中添加同意的小产品
            afterOrder.setAfterProductList(mapper.listAgree(afterOrder.getId()));
        }
        return afterOrderslist;
    }

    /**
     * 团订售后详情下的平台收货下数据
     *
     * @param afterOrderID 售后订单ID
     */
    @Override
    public List<MlccTrackAfterOrder> receiving(String afterOrderID) {
        QueryWrapper<MlccTrackAfterOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("after_order_id", afterOrderID).eq("status", 10);
        return trackAfterOrderMapper.selectList(wrapper);
    }

    /**
     * 团订售后订单详情平台发货的【确认收货】 或 【提交】
     *
     * @param afterOrderID 售后订单表ID
     * @param trackAfterID 操作的售后订单跟踪表ID
     * @param type         0 提交，1 确认收货
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int receiptsOrSubmit(String afterCode, String afterOrderID, String trackAfterID, Integer type, String remarks) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 原来的售后订单跟踪表数据
        MlccTrackAfterOrder trackAfterOrder = trackAfterOrderMapper.selectById(trackAfterID);
        if (type == 0) { // 如果是提交，新增一条售后跟踪记录
            // 往售后订单跟踪表添加新的记录
            MlccTrackAfterOrder order = new MlccTrackAfterOrder();
            order.setId(UUID.randomUUID().toString().substring(0, 15)).setAfterOrderId(afterOrderID).setTrackCode(UUID.randomUUID().toString().substring(0, 15))
                    .setType(2).setReason(remarks).setAfterSalesType(0).setRemark(remarks).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname())
                    .setSysOrgCode(user.getOrgCode()).setStatus(0);
            int insert = trackAfterOrderMapper.insert(order);
            System.out.println("添加售后跟踪成功了吗？" + insert);
            // 往售后小产品表添加记录（把原来售后订单跟踪表下的小产品复制一份，放到新添加的售后顶动跟踪表下，产生新的关联）
            if (insert > 0) {
                System.out.println(trackAfterID);
                QueryWrapper<MlccTrackafterorderPerson> wrapper = new QueryWrapper<>();
                wrapper.eq("track_after_order_id", trackAfterID);
                List<MlccTrackafterorderPerson> personList = trackafterorderPersonMapper.selectList(wrapper);
                for (MlccTrackafterorderPerson person : personList) {
                    MlccTrackafterorderPerson person1 = new MlccTrackafterorderPerson();
                    person1.setTrackAfterOrderId(order.getId()).setSmallProductId(person.getSmallProductId()).setAfterSn(afterCode)
                            .setRemark(remarks).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname()).setSysOrgCode(user.getOrgCode());
                    if (type == 1) {
                        person1.setType(3);
                    } else if (type == 0) {
                        person1.setType(2);
                    }
                    int addPersonResult = trackafterorderPersonMapper.insert(person1);
                    if (addPersonResult < 1) {
                        new RuntimeException("插入售后小产品表失败");
                        return 0;
                    }
                }
                return 1;
            } else {
                return 0;
            }
        } else if (type == 1) { // 如果是确认收货，新增一条成功的记录（更新原来的状态为10的售后订单记录）
            // 原来那条已发货的记录添加标记
            trackAfterOrder.setUpdateBy(user.getRealname()).setIsGet(1);
            int updateResult = trackAfterOrderMapper.updateById(trackAfterOrder);
            if (updateResult > 0) {
                // 插入一条确认收货的数据，状态为 5
                // 往售后订单跟踪表添加新的记录
                MlccTrackAfterOrder myget = new MlccTrackAfterOrder();
                myget.setId(UUID.randomUUID().toString().substring(0, 15)).setAfterOrderId(afterOrderID).setTrackCode(UUID.randomUUID().toString().substring(0, 15))
                        .setType(2).setReason(remarks).setRemark(remarks).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname())
                        .setSysOrgCode(user.getOrgCode()).setStatus(5);
                int insert = trackAfterOrderMapper.insert(myget);
                if (insert > 0) {
                    // 前端需要展示已收货的人员，这里插入数据
                    QueryWrapper<MlccTrackafterorderPerson> addShouhuo = new QueryWrapper<>();
                    addShouhuo.eq("track_after_order_id", trackAfterID);
                    List<MlccTrackafterorderPerson> shouHuoList = trackafterorderPersonMapper.selectList(addShouhuo);
                    if (shouHuoList != null && shouHuoList.size() > 0) {
                        shouHuoList.stream().forEach(yisou -> {
                            yisou.setType(3).setUpdateBy(user.getRealname()).setTrackAfterOrderId(myget.getId()).setId(null);
                            trackafterorderPersonMapper.insert(yisou);
                        });
                    }
                }

                /*// 更新一下名下的售后小产品的状态，改为已收货*/
                /*QueryWrapper<MlccTrackafterorderPerson> wrapper = new QueryWrapper<>();
                wrapper.eq("track_after_order_id", trackAfterID);
                List<MlccTrackafterorderPerson> personList = trackafterorderPersonMapper.selectList(wrapper);
                personList.stream().forEach(afterPro -> {
                    afterPro.setType(3).setUpdateBy(user.getRealname());
                    trackafterorderPersonMapper.updateById(afterPro);
                });*/
                return 1;
            }
            return 0;
        } else { // 啥也不是
            return 0;
        }
    }

    /**
     * 个订售后订单详情平台发货的【确认收货】 或 【提交】
     *
     * @param afterCode    售后订单编码
     * @param afterOrderID 售后订单表ID
     * @param trackAfterID 操作的售后订单跟踪表ID
     * @param type         0 提交，1 确认收货
     * @param remarks      备注
     */
    @Override
    public int receiptsOrSubmitSingle(String afterCode, String afterOrderID, String trackAfterID, Integer type, String remarks) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 售后订单基本信息
        MlccAfterSalesinfo afterSalesinfo = afterSalesinfoMapper.selectById(afterOrderID);
        /*原来的售后订单跟踪表数据*/
        MlccTrackAfterOrder trackAfterOrder = trackAfterOrderMapper.selectById(trackAfterID);
        // 如果是提交，新增一条售后跟踪记录
        if (type == 0) {
            // 往售后订单跟踪表添加新的记录
            MlccTrackAfterOrder order = new MlccTrackAfterOrder();
            order.setId(UUID.randomUUID().toString()).setAfterOrderId(afterOrderID).setTrackCode(UUID.randomUUID().toString()).setType(1)
                    .setReason(remarks).setAfterSalesType(2).setRemark(remarks).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname())
                    .setSysOrgCode(user.getOrgCode()).setStatus(0);
            return trackAfterOrderMapper.insert(order);
        } else if (type == 1) {
            // 如果是确认收货，更新原来的售后订单跟踪表
            trackAfterOrder.setStatus(5).setUpdateBy(user.getRealname()).setRemark(remarks);
            afterSalesinfo.setAfterstatus(5);
            afterSalesinfoMapper.updateById(afterSalesinfo);
            return trackAfterOrderMapper.updateById(trackAfterOrder);
        } else {
            // 啥也不是
            return 0;
        }
    }

    /**
     * 产品已收列表
     *
     * @param afterCode 售后订单编号
     */
    @Override
    public List<MyAfterProduct> listProductget(String afterCode) {
        return mapper.listProductget(afterCode);
    }

    /**
     * 更新产品状态
     *
     * @param id 售后产品ID
     */
    @Override
    public int updateAfterPro(String id, Integer status) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<MlccTrackafterorderPerson> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id).eq("type", 3);
        MlccTrackafterorderPerson person = trackafterorderPersonMapper.selectOne(wrapper);
        person.setStatus(status).setUpdateBy(user.getRealname());
        return trackafterorderPersonMapper.updateById(person);
    }

    /**
     * 根据批次名称查询批次基本信息
     *
     * @param orderSn   团订订单编号
     * @param batchName 批次名称
     */
    @Override
    public MlccTrackingTeamDepart getBatchByCode(String orderSn, String batchName) {
        MlccTrackingTeamDepart batch = mapper.getBatchByCode(orderSn, batchName);
        // 查询批次下的装箱单
        if (batch != null) {
            QueryWrapper<MlccBatchPackingInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("batch_id", batch.getId());
            batch.setBatchPackingInfoList(batchPackingInfoMapper.selectList(wrapper));
        }
        return batch;
    }

    /**
     * 把已入库的产品添加到装箱单
     *
     * @param batchID    批次ID
     * @param packageID  装箱单ID
     * @param productIDS 选中的产品id数组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addProductonBox(String batchID, String packageID, String[] productIDS) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (productIDS != null && productIDS.length > 0) {
            for (String productID : productIDS) {
                QueryWrapper<MlccTrackafterorderPerson> wrapper = new QueryWrapper<>();
                wrapper.eq("id", productID).eq("status", 3);
                MlccTrackafterorderPerson person = trackafterorderPersonMapper.selectOne(wrapper);
                if (person != null) {
                    person.setPiciId(batchID).setPackingId(packageID).setUpdateBy(user.getRealname());
                    int i = trackafterorderPersonMapper.updateById(person);
                    if (i < 1) {
                        return 0;
                    }
                }
            }
            return 1;
        }
        return 0;
    }

    /**
     * 批次装箱的保存功能（在添加产品之后）（可以准备发货了）
     *
     * @param adterCode    售后订单编号
     * @param remark       备注
     * @param afterOrderId 售后订单ID
     * @param packageid    装箱单id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveProInPPackage(String adterCode, String remark, String afterOrderId, String packageid) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // 售后订单表的基本信息
        MlccAfterSalesinfo salesinfo = afterSalesinfoMapper.selectById(afterOrderId);

        // 查询之前已收货的售后小产品
        QueryWrapper<MlccTrackafterorderPerson> wrapper = new QueryWrapper<>();
        wrapper.eq("after_sn", adterCode).isNotNull("packing_id").isNotNull("pici_id")
                .eq("type", 3);
        List<MlccTrackafterorderPerson> personList = trackafterorderPersonMapper.selectList(wrapper);
        if (personList != null && personList.size() > 0) {

            // 向售后订单跟踪表添加一条记录
            MlccTrackAfterOrder afterOrder = new MlccTrackAfterOrder();
            afterOrder.setId(UUID.randomUUID().toString()).setAfterOrderId(afterOrderId).setTrackCode(UUID.randomUUID().toString())
                    .setType(2).setReason("售后小产品装箱的保存操作").setAfterSalesType(salesinfo.getAfterSalesType()).setRemark(remark)
                    .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname()).setSysOrgCode(user.getOrgCode()).setStatus(8);
            int insert = trackAfterOrderMapper.insert(afterOrder);
            if (insert > 0) {
                for (MlccTrackafterorderPerson person : personList) {
                    // 插入状态为 发货
                    person.setType(4).setUpdateBy(user.getRealname()).setStatus(4).setTrackAfterOrderId(afterOrder.getId());
                    int i = trackafterorderPersonMapper.updateById(person);
                    MlccTrackafterorderXpPacking xpPacking = new MlccTrackafterorderXpPacking();
                    xpPacking.setPackingId(packageid).setAfterSmallProductId(person.getId() + "").setRemark(remark).setCreateBy(user.getRealname())
                            .setUpdateBy(user.getRealname()).setSysOrgCode(user.getOrgCode());
                    xpPackingMapper.insert(xpPacking);
                    if (i < 1) {
                        return 0;
                    }
                }
                return 1;
            } else {
                return 0;
            }
        }
        return 0;
    }

    /**
     * 前端展示售后产品发货列表
     *
     * @param afterCode 售后订单编号
     */
    @Override
    public List<MyAfterProduct> outAfterPro(String afterCode) {
        return mapper.outAfterPro(afterCode);
    }

    /**
     * 售后尺寸列表
     *
     * @param smallProid 售后小产品ID
     * @param afterCode  售后订单编号
     */
    @Override
    public List<MyBodySizeInfo> listAfterSize(String smallProid, String afterCode, Integer isafter) {
        if (isafter == 1) {
            return mapper.getAfterSize(smallProid, afterCode);
        } else {
            return mapper.getReAfterSize(smallProid, afterCode);
        }
    }

    /**
     * 面料售后的同意或拒绝
     *
     * @param afterID 售后订单ID
     * @param remark  备注
     * @param isAgree 1拒绝，2通过审核（接受）
     */
    @Override
    public int fabricOrderAfterIsAagree(String afterID, String remark, Integer isAgree) throws Exception {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 售后订单基本信息
        MlccAfterSalesinfo afterSalesinfo = afterSalesinfoMapper.selectById(afterID);

        // 往售后订单跟踪表添加数据
        MlccTrackAfterOrder trackAfterOrder = new MlccTrackAfterOrder();
        trackAfterOrder.setId(UUID.randomUUID().toString()).setAfterOrderId(afterID).setTrackCode(UUID.randomUUID().toString())
                .setType(0).setAfterSalesType(afterSalesinfo.getAfterSalesType()).setStatus(isAgree).setRemark(remark)
                .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname()).setSysOrgCode(user.getOrgCode())
                .setReason(remark);
        int insert = trackAfterOrderMapper.insert(trackAfterOrder);
        if (insert > 0) {
            // 如果同意售后
            if (isAgree == 2) {
                Thread.sleep(1000);
                MlccTrackAfterOrder agree = new MlccTrackAfterOrder();
                agree.setId(UUID.randomUUID().toString()).setAfterOrderId(afterID).setTrackCode(UUID.randomUUID().toString())
                        .setType(0).setAfterSalesType(afterSalesinfo.getAfterSalesType()).setStatus(4).setRemark(remark)
                        .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname()).setSysOrgCode(user.getOrgCode())
                        .setReason(remark);
                int insert2 = trackAfterOrderMapper.insert(agree);
            } else if (isAgree == 1) {
                // 订单状态改为售后完成（前端可以继续售后）,状态是11
                MlccFabricOrderinfo fabricOrderinfo = fabricOrderinfoMapper.selectById(afterSalesinfo.getOrderId());
                fabricOrderinfo.setStatus(11);
                fabricOrderinfoMapper.updateById(fabricOrderinfo);
            }
            // 更新售后订单的状态
            afterSalesinfo.setAfterstatus(isAgree).setUpdateBy(user.getRealname());
            afterSalesinfoMapper.updateById(afterSalesinfo);
        }
        return insert;
    }

    /**
     * 面料、个订 订单售后已拒绝
     *
     * @param afterID 售后订单ID
     */
    @Override
    public List<MlccTrackAfterOrder> fabricAfterOrderRefuse(String afterID) {
        QueryWrapper<MlccTrackAfterOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("after_order_id", afterID).eq("status", 1);
        return trackAfterOrderMapper.selectList(wrapper);
    }

    /**
     * 面料、个订 订单售后已接受
     *
     * @param afterID 售后订单ID
     */
    @Override
    public List<MlccTrackAfterOrder> fabricAfterOrderAgree(String afterID) {
        QueryWrapper<MlccTrackAfterOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("after_order_id", afterID).eq("status", 2);
        return trackAfterOrderMapper.selectList(wrapper);
    }

    /**
     * 个订 订单售后后台发货
     *
     * @param afterID 售后订单ID
     */
    @Override
    public List<MlccTrackAfterOrder> isFahuo(String afterID) {
        QueryWrapper<MlccTrackAfterOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("after_order_id", afterID).eq("status", 8);
        return trackAfterOrderMapper.selectList(wrapper);
    }

    /**
     * 个订售后详情获取产品返修尺寸数据
     *
     * @param orderSn   个订订单编号
     * @param afterCode 售后订单编号
     */
    @Override
    public List<Myproduct> listSingleAfterProductSize(String orderSn, String afterCode) {
        QueryWrapper<MlccAfterSalesinfo> wrapper = new QueryWrapper<>();
        wrapper.eq("after_code", afterCode);
        MlccAfterSalesinfo afterSalesinfo = afterSalesinfoMapper.selectOne(wrapper);
        List<Myproduct> productList = mapper.listSingleAfterProduct(orderSn, afterCode);
        if (productList != null && productList.size() > 0) {
            for (int i = 0; i < productList.size(); i++) {
                if (productList.get(i).getProductId().equals(afterSalesinfo.getProductId())) {
                    productList.get(i).setBodySizeInfos(mapper.listSingleAfterProductSize(productList.get(i).getProductId(), orderSn, afterCode));
                } else {
                    productList.remove(i);
                }
            }
        }
        return productList;
    }

    /**
     * 个订售后的同意或者拒绝
     *
     * @param afterID  售后订单ID
     * @param remark   填写的备注
     * @param isAgree  是否同意 1拒绝，2通过审核
     * @param saddress 收货地址
     * @param sperson  收货人
     * @param sphone   收货电话
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int singlrAfterOrderIsAgree(String afterID, String remark, Integer isAgree, String saddress, String sperson, String sphone) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 售后订单基本信息
        MlccAfterSalesinfo afterSalesinfo = afterSalesinfoMapper.selectById(afterID);

        // 往售后订单跟踪表添加数据(同意或拒绝)
        MlccTrackAfterOrder trackAfterOrder = new MlccTrackAfterOrder();
        trackAfterOrder.setId(UUID.randomUUID().toString()).setAfterOrderId(afterID).setTrackCode(UUID.randomUUID().toString())
                .setType(1).setAfterSalesType(afterSalesinfo.getAfterSalesType()).setStatus(isAgree).setRemark(remark)
                .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname()).setSysOrgCode(user.getOrgCode())
                .setReason(remark).setSaddress(saddress).setSperson(sperson).setSphone(sphone);
        int insert = trackAfterOrderMapper.insert(trackAfterOrder);
        if (insert > 0) {
            // 如果驳回了售后，需要退钱！
            if (isAgree == 1) {
                rejectedAfter(afterSalesinfo.getId().toString(), afterSalesinfo.getUserId());
                // 将售后订单改为驳回状态
                afterSalesinfo.setAfterstatus(1);
                afterSalesinfoMapper.updateById(afterSalesinfo);
            } else if (isAgree == 2) {
                // 如果是同意售后，启用返修参数
                orderService.takeonFanxiuChengben(afterSalesinfo.getOrderSn(), afterSalesinfo.getAfterCode());
                // 往售后订单跟踪表添加数据(发货)
                MlccTrackAfterOrder fahuo = new MlccTrackAfterOrder();
                fahuo.setId(UUID.randomUUID().toString()).setAfterOrderId(afterID).setTrackCode(UUID.randomUUID().toString())
                        .setType(1).setAfterSalesType(afterSalesinfo.getAfterSalesType()).setStatus(4).setRemark(remark)
                        .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname()).setSysOrgCode(user.getOrgCode())
                        .setReason(remark).setSaddress(saddress).setSperson(sperson).setSphone(sphone);
                trackAfterOrderMapper.insert(fahuo);
            }
        }
        return insert;
    }

    /**
     * 个订售后，产品已收列表
     *
     * @param afterID 售后订单ID
     */
    @Override
    public MlccAfterSalesinfo SingleProGet(String afterID) {
        QueryWrapper<MlccAfterSalesinfo> wrapper = new QueryWrapper<>();
        wrapper.eq("id", afterID).eq("afterstatus", 5);
        return afterSalesinfoMapper.selectOne(wrapper);
    }

    /**
     * 个订售后更新产品状态
     *
     * @param afterID 售后订单ID
     * @param status  产品状态
     */
    @Override
    public int updateSingleAfterOrder(String afterID, String status) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 存储最后的结果
        int result = 0;
        // 找到这条售后订单
        MlccAfterSalesinfo afterSalesinfo = afterSalesinfoMapper.selectById(afterID);
        afterSalesinfo.setAfterProStatus(status).setUpdateBy(user.getRealname());
        return afterSalesinfoMapper.updateById(afterSalesinfo);
    }

    /**
     * 个订售后售后订单发货
     *
     * @param afterID 售后订单id
     * @param remark  备注
     * @param kdid    快递id
     * @param number  运单号
     */
    @Override
    public int sproductFahuo(String afterID, String remark, String kdid, String number) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MlccAfterSalesinfo afterSalesinfo = afterSalesinfoMapper.selectById(afterID);
        afterSalesinfo.setAfterstatus(4).setUpdateBy(user.getRealname()).setRemark(remark);
        int i = afterSalesinfoMapper.updateById(afterSalesinfo);
//        if (i > 0) {
        //向售后订单跟踪表添加记录，状态未发货8
        // 往售后订单跟踪表添加新的记录
        MlccTrackAfterOrder order = new MlccTrackAfterOrder();
        order.setId(UUID.randomUUID().toString()).setAfterOrderId(afterID).setTrackCode(UUID.randomUUID().toString()).setType(1)
                .setReason(remark).setAfterSalesType(afterSalesinfo.getAfterSalesType()).setRemark(remark).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname())
                .setSysOrgCode(user.getOrgCode()).setStatus(8).setKuaidiId(kdid).setThirdSn(number);
        trackAfterOrderMapper.insert(order);
//        }
        return i;
    }

    /**
     * 个订产品状态跟踪更新产品状态(向产品状态跟踪表添加一条记录)
     *
     * @param productID 产品ID
     * @param orderSn   个订订单编号
     */
    @Override
    public int updateProductStatus(String productID, String orderSn, Integer status, String name, String remark, String wrater) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MlccTrackingProduct trackingProduct = new MlccTrackingProduct();
        trackingProduct.setId(UUID.randomUUID().toString()).setProductId(productID).setStatus(status).setWrater(wrater)
                .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname()).setSysOrgCode(user.getOrgCode())
                .setOrderSn(orderSn).setStatusName(name).setRemark(remark);
        return trackingProductMapper.insert(trackingProduct);
    }

    /**
     * 面料售后订单详情平台发货的【确认收货】 或 【提交】
     *
     * @param afterCode    售后订单编码
     * @param afterOrderID 售后订单表ID
     * @param trackAfterID 操作的售后订单跟踪表ID
     * @param type         0 提交，1 确认收货
     * @param remarks      备注
     */
    @Override
    public int fabricAafterupdate(String afterCode, String afterOrderID, String trackAfterID, Integer type, String remarks) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 这条售后订单信息
        MlccAfterSalesinfo salesinfo = afterSalesinfoMapper.selectById(afterOrderID);
        // 面料订单基本信息
        MlccFabricOrderinfo orderinfo = fabricOrderinfoMapper.selectById(salesinfo.getOrderId());
        /*原来的售后订单跟踪表数据*/
        MlccTrackAfterOrder trackAfterOrder = trackAfterOrderMapper.selectById(trackAfterID);
        // 如果是提交，新增一条售后跟踪记录
        if (type == 0) {
            // 往售后订单跟踪表添加新的记录
            MlccTrackAfterOrder order = new MlccTrackAfterOrder();
            order.setId(UUID.randomUUID().toString()).setAfterOrderId(afterOrderID).setTrackCode(UUID.randomUUID().toString()).setType(0)
                    .setReason(remarks).setAfterSalesType(salesinfo.getAfterSalesType()).setRemark(remarks).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname())
                    .setSysOrgCode(user.getOrgCode()).setStatus(0);
            return trackAfterOrderMapper.insert(order);
        } else if (type == 1) {
            // 如果是确认收货，更新原来的售后订单跟踪表
            trackAfterOrder.setStatus(5).setUpdateBy(user.getRealname()).setRemark(remarks).setReason(remarks);
            // 向退款申请表添加一条记录 （如果是退货）
            if (salesinfo.getAfterSalesType() == 0) {
                MlccApplyRefundmoney applyRefundmoney = new MlccApplyRefundmoney();
                applyRefundmoney.setOrderSn(salesinfo.getOrderSn()).setOrderType(0).setReturnMoney(salesinfo.getAfterPrice())
                        .setStatus(0).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname()).setReason("面料退货")
                        .setCartId(salesinfo.getCartId())
                        .setOrderMoney(orderinfo.getOrderMoney()).setUserId(salesinfo.getUserId()).setOrderAfterId(afterOrderID);
                refundmoneyMapper.insert(applyRefundmoney);
            }
            return trackAfterOrderMapper.updateById(trackAfterOrder);
        } else {
            // 啥也不是
            return 0;
        }
    }

    /**
     * 面料售后的产品已收
     *
     * @param afterOrderID 售后订单ID
     */
    @Override
    public List<MlccTrackAfterOrder> fabricAafteryishou(String afterOrderID) {
        QueryWrapper<MlccTrackAfterOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("after_order_id", afterOrderID).eq("status", 5).eq("type", 0);
        return trackAfterOrderMapper.selectList(wrapper);
    }

    /**
     * 换货的面料售后订单  发货
     *
     * @param afterOrderID 售后订单ID
     * @param number       运单号
     * @param trackid      需要发货的售后订单跟踪id
     */
    @Override
    public int fabricAfterFahuo(String afterOrderID, String number, String trackid, String kdid, String remake) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        /*原来的售后订单跟踪表数据*/
        MlccTrackAfterOrder trackAfterOrder = trackAfterOrderMapper.selectById(trackid);
        // 这条售后订单信息
        MlccAfterSalesinfo salesinfo = afterSalesinfoMapper.selectById(afterOrderID);
        // 向售后订单跟踪表添加一条发货的记录
        MlccTrackAfterOrder order = new MlccTrackAfterOrder();
        order.setId(UUID.randomUUID().toString()).setAfterOrderId(afterOrderID).setTrackCode(UUID.randomUUID().toString()).setType(0)
                .setReason(remake).setAfterSalesType(salesinfo.getAfterSalesType()).setRemark(remake).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname())
                .setSysOrgCode(user.getOrgCode()).setStatus(8).setThirdSn(number).setKuaidiId(kdid).setRemark(remake);
        // 更新已收的那条记录
        trackAfterOrder.setIsFahuo(1);
        trackAfterOrderMapper.updateById(trackAfterOrder);
        // 这条售后订单改为已发货
        salesinfo.setAfterstatus(5);
        afterSalesinfoMapper.updateById(salesinfo);
        return trackAfterOrderMapper.insert(order);
    }

    /**
     * 个订订单成本 面料成本
     *
     * @param orderSn 个订订单成本
     */
    @Override
    public List<MlccFabricInfo> SingleChengbenFabric(String orderSn) {
        // 用来保存所有的面料
        ArrayList<MlccFabricInfo> fabricInfos = new ArrayList<>();
        // 查询这个订单下的所有产品
        QueryWrapper<MlccProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        List<MlccProductInfo> productInfos = productInfoMapper.selectList(wrapper);
        if (productInfos != null && productInfos.size() > 0) {
            productInfos.stream().forEach(pro -> {
                // 拿到产品的面料
                String fabricIds = pro.getFabricIds();
                if (fabricIds != null) {
                    String[] idAandMishu = fabricIds.split(",");
                    if (idAandMishu != null && idAandMishu.length > 0) {
                        for (String fabricidmishu : idAandMishu) {
                            String[] split = fabricidmishu.split("/");
                            MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(split[0]);
                            if (fabricInfo != null) {
                                fabricInfo.setMishu(split[1]);
                                if (split[1] != null) {
                                    if (fabricInfo.getFabricPrice() == null && fabricInfo.getGroupId() != null) {
                                        // 获取面料的价格
                                        fabricUtil.addPrice(fabricInfo, Double.valueOf(split[1]));
                                    }
                                    fabricInfo.setAllPrice(fabricInfo.getFabricPrice().doubleValue() * Double.valueOf(split[1]))
                                            .setJiesuanMpney(pro.getFabricSettleMoney().doubleValue()).setJiesuan(pro.getIsDuizhang())
                                            .setCreateTime(pro.getCreateTime());
                                    fabricInfos.add(fabricInfo);
                                }
                            }
                        }
                    }
                }
            });
        }
        return fabricInfos;
    }

    /**
     * 团订订单的面料成本
     *
     * @param orderSn 团订订单编号
     */
    @Override
    public List<MlccFabricInfo> teamFabricCB(String orderSn) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 用来保存所有的面料
        ArrayList<MlccFabricInfo> fabricInfos = new ArrayList<>();
        // 得到团订订单下的所有小产品，分组为大产品
        List<MyteamPriceProduct> products = orderAafterTMapper.listpriceProduuct(orderSn);
        if (products != null && products.size() > 0) {
            // 遍历每个大产品
            for (MyteamPriceProduct product : products) {
                // 查到这个大产品的基本信息
                MlccProductInfo productInfo = productInfoMapper.selectById(product.getProductId());
                if (productInfo != null) {
                    // 拿到产品的面料
                    String fabricIds = productInfo.getFabricIds();
                    if (fabricIds != null) {
                        String[] idAandMishu = fabricIds.split(",");
                        if (idAandMishu != null && idAandMishu.length > 0) {
                            for (String fabricidmishu : idAandMishu) {
                                String[] split = fabricidmishu.split("/");
                                MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(split[0]);
                                if (fabricInfo != null) {
                                    fabricInfo.setMishu(split[1]);
                                    if (split[1] != null) {
//                                        if (fabricInfo.getFabricPrice() == null && fabricInfo.getGroupId() != null) {
                                        // 查询是否修改过面料米数
                                        QueryWrapper<MlccOrderFabric> wrapper = new QueryWrapper<>();
                                        wrapper.eq("order_sn", orderSn).eq("fabric_id", fabricInfo.getId());
                                        MlccOrderFabric orderFabric = orderFabricMapper.selectOne(wrapper);
                                        if (orderFabric != null && orderFabric.getMishu() != null) {
                                            fabricInfo.setMishu(orderFabric.getMishu());
                                        }
                                        // 获取面料的价格
                                        fabricUtil.addPrice(fabricInfo, Double.valueOf(fabricInfo.getMishu()));
//                                        }
                                        // 计算成本价格等信息
                                        // 计算价格
                                        BigDecimal add = fabricInfo.getFabricPrice().add(new BigDecimal(Double.valueOf(fabricInfo.getMishu()))).add(new BigDecimal(product.getNum()));
                                        // 米数
                                        BigDecimal allMishu = new BigDecimal(Double.valueOf(fabricInfo.getMishu())).add(new BigDecimal(product.getNum()));

                                        fabricInfo.setAllPrice(add.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue())
                                                .setMishu(allMishu.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "")
                                                .setJiesuanMpney(productInfo.getFabricSettleMoney().doubleValue()).setJiesuan(productInfo.getIsDuizhang())
                                                .setCreateTime(productInfo.getCreateTime());
                                        fabricInfos.add(fabricInfo);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return fabricInfos;
    }

    /**
     * 供应商派单之后，插入成本列表数据（个订）
     *
     * @param orderSn 订单编号
     * @param gysid   供应商ID
     * @return int
     */
    @Override
    public int savePaidanChengben(String orderSn, String gysid) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取个订订单下的所有产品
        List<MlccProductInfo> productInfos = singleUtil.listProFromSingleOrder(orderSn);
        if (productInfos != null && productInfos.size() > 0) {
            for (MlccProductInfo productInfo : productInfos) {
                // 获取当前产品的品类ID
                String PLID = fabricUtil.getpingleiFromProduct(productInfo);
                if (PLID != null) {
                    // 确定工厂的价格体系
                    MlccPricesystemFactoryCategory factoryCategory = singleUtil.factoryCategory(gysid, PLID, 0, 0);
                    if (factoryCategory != null) {
                        // 获取这个类型下供应商设置的所有成本
                        List<MlccPriceSystemFactoryRecord> records = singleUtil.listFactoryRecord(PLID, factoryCategory.getId() + "");
                        System.out.println("查到的成本项：" + records);
                        if (records != null && records.size() > 0) {
                            for (MlccPriceSystemFactoryRecord record : records) {
                                MlccPaidanOrderCost paidanOrderCost = new MlccPaidanOrderCost();
                                paidanOrderCost.setSysuserId(gysid).setOrderSn(orderSn).setOrderType(1).setCostItem(record.getCostItem())
                                        .setCostName(record.getCostName()).setCostId(record.getCostId()).setPrice(record.getPrice())
                                        .setType(record.getType()).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname());
                                int insert = paidanOrderCostMapper.insert(paidanOrderCost);
                                if (insert < 1) {
                                    return 0;
                                }
                            }
                        }
                    }
                }

            }
        }
        return 1;
    }

    /**
     * 供应商派单之后，插入工艺成本数据（个订）不用
     *
     * @param orderSn 订单编号
     * @param gysid   供应商ID
     * @return int
     */
    @Override
    public int savePaidanGY(String orderSn, String gysid) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取个订订单下的所有产品
        List<MlccProductInfo> productInfos = singleUtil.listProFromSingleOrder(orderSn);
        if (productInfos != null && productInfos.size() > 0) {
            for (MlccProductInfo productInfo : productInfos) {
                // 获取产品的工艺类型ID
                String gylx = fabricUtil.getGYLXFromProduct(productInfo);
                if (gylx != null) {
                    // 确定工厂的价格体系
                    MlccPricesystemFactoryCategory factoryCategory = singleUtil.factoryCategory(gysid, gylx, 0, 1);
                    if (factoryCategory != null) {
                        // 确定价格区间
                        MlccPricesystemFactoryRange range = singleUtil.getrange(factoryCategory.getId() + "", 1);
                        if (range != null) {
                            // 向派单工艺成本表添加记录
                            MlccPaidanOrderGongyi paidanOrderGongyi = new MlccPaidanOrderGongyi();
                            paidanOrderGongyi.setSysuserId(gysid).setOrderSn(orderSn).setOrderType(1).setCategoryId(gylx).setCostPrice(range.getPrice())
                                    .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname());
                            int insert = paidanOrderGongyiMapper.insert(paidanOrderGongyi);
                            if (insert < 1) {
                                return 0;
                            }
                        }
                    }
                }
            }
        }
        return 1;
    }

    /**
     * 供应商派单之后，插入成本列表数据（团订）
     *
     * @param orderSn 订单编号
     * @param gysid   供应商ID
     * @return int
     */
    public int savePaidanChengbenTean(String orderSn, String gysid) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 得到团订订单下的所有小产品，分组为大产品
        List<MyteamPriceProduct> products = orderAafterTMapper.listpriceProduuct(orderSn);
        if (products != null && products.size() > 0) {
            for (MyteamPriceProduct product : products) {
                // 查到这个大产品的基本信息
                MlccProductInfo productInfo = productInfoMapper.selectById(product.getProductId());
                if (productInfo != null) {
                    // 获取当前产品的品类ID
                    String PLID = fabricUtil.getpingleiFromProduct(productInfo);

                    // 查询这个产品下的标准码尺寸 小产品数量
                    QueryWrapper<MlccCustomerProductInfo> bzmWrapper = new QueryWrapper<>();
                    bzmWrapper.eq("team_order_sn", orderSn).eq("product_id", productInfo.getId())
                            .eq("is_after", 0).eq("bodys_type", 1);
                    int bzmcount = smallProductMapper.selectCount(bzmWrapper);

                    // 查询这个产品下的团订尺寸 小产品数量(自定义尺码)
                    QueryWrapper<MlccCustomerProductInfo> tdWrapper = new QueryWrapper<>();
                    tdWrapper.eq("team_order_sn", orderSn).eq("product_id", productInfo.getId())
                            .eq("is_after", 0).eq("bodys_type", 0);
                    int tdmcount = smallProductMapper.selectCount(tdWrapper);

                    if (PLID != null) {
                        if (bzmcount > 0) {
                            // 确定工厂的价格体系
                            MlccPricesystemFactoryCategory factoryCategory = singleUtil.factoryCategory(gysid, PLID, 2, 0);
                            if (factoryCategory != null) {
                                // 获取这个类型下供应商设置的所有成本
                                List<MlccPriceSystemFactoryRecord> records = singleUtil.listFactoryRecord(PLID, factoryCategory.getId() + "");
                                System.out.println("查到的成本项：" + records);
                                if (records != null && records.size() > 0) {
                                    for (MlccPriceSystemFactoryRecord record : records) {
                                        MlccPaidanOrderCost paidanOrderCost = new MlccPaidanOrderCost();
                                        paidanOrderCost.setSysuserId(gysid).setOrderSn(orderSn).setOrderType(2).setCostItem(record.getCostItem())
                                                .setCostName(record.getCostName()).setCostId(record.getCostId()).setPrice(record.getPrice())
                                                .setProductId(productInfo.getId())
                                                .setType(record.getType()).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname()).setNum(bzmcount);
                                        int insert = paidanOrderCostMapper.insert(paidanOrderCost);
                                        if (insert < 1) {
                                            return 0;
                                        }
                                    }
                                }
                            }
                        }

                        if (tdmcount > 0) {
                            // 确定工厂的价格体系
                            MlccPricesystemFactoryCategory factoryCategory = singleUtil.factoryCategory(gysid, PLID, 1, 0);
                            if (factoryCategory != null) {
                                // 获取这个类型下供应商设置的所有成本
                                List<MlccPriceSystemFactoryRecord> records = singleUtil.listFactoryRecord(PLID, factoryCategory.getId() + "");
                                System.out.println("查到的成本项：" + records);
                                if (records != null && records.size() > 0) {
                                    for (MlccPriceSystemFactoryRecord record : records) {
                                        MlccPaidanOrderCost paidanOrderCost = new MlccPaidanOrderCost();
                                        paidanOrderCost.setSysuserId(gysid).setOrderSn(orderSn).setOrderType(2).setCostItem(record.getCostItem())
                                                .setCostName(record.getCostName()).setCostId(record.getCostId()).setPrice(record.getPrice())
                                                .setProductId(productInfo.getId())
                                                .setType(record.getType()).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname()).setNum(tdmcount);
                                        int insert = paidanOrderCostMapper.insert(paidanOrderCost);
                                        if (insert < 1) {
                                            return 0;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return 0;
    }

    /**
     * 供应商派单之后，插入工艺成本数据（团订）
     *
     * @param orderSn 订单编号
     * @param gysid   供应商ID
     * @return int
     */
    @Override
    public int savePaidanGYTeam(String orderSn, String gysid) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 得到团订订单下的所有小产品，分组为大产品
        List<MyteamPriceProduct> products = orderAafterTMapper.listpriceProduuct(orderSn);
        if (products != null && products.size() > 0) {
            for (MyteamPriceProduct product : products) {
                // 查到这个大产品的基本信息
                MlccProductInfo productInfo = productInfoMapper.selectById(product.getProductId());
                if (productInfo != null) {
                    // 获取产品的工艺类型ID
                    String gylx = fabricUtil.getGYLXFromProduct(productInfo);
                    String plid = fabricUtil.getpingleiFromProduct(productInfo);

                    // 查询这个产品下的标准码尺寸 小产品数量
                    QueryWrapper<MlccCustomerProductInfo> bzmWrapper = new QueryWrapper<>();
                    bzmWrapper.eq("team_order_sn", orderSn).eq("product_id", productInfo.getId())
                            .eq("is_after", 0).eq("bodys_type", 1);
                    int bzmcount = smallProductMapper.selectCount(bzmWrapper);

                    // 查询这个产品下的团订尺寸 小产品数量
                    QueryWrapper<MlccCustomerProductInfo> tdWrapper = new QueryWrapper<>();
                    tdWrapper.eq("team_order_sn", orderSn).eq("product_id", productInfo.getId())
                            .eq("is_after", 0).eq("bodys_type", 0);
                    int tdmcount = smallProductMapper.selectCount(tdWrapper);

                    if (gylx != null) {
                        // 这是原来的工艺类型对象，没有设置折扣
                        MlccCategoryInfo categoryInfo = categoryInfoMapper.selectById(gylx);
                        /*注意：需要重新定位到真正的工艺id，此时查到的是前端展示，与设置折扣的工艺不是同一个，但是编号相同*/
                        QueryWrapper<MlccCategoryInfo> wrapper1 = new QueryWrapper<>();
                        wrapper1.eq("category_code", categoryInfo.getCategoryCode()).eq("topid", plid)
                                .eq("is_type", 4).eq("status", 0);
                        // 这是查询到了设置了折扣的工艺
                        MlccCategoryInfo newCategoryInfo = categoryInfoMapper.selectOne(wrapper1);
                        if (newCategoryInfo != null) {
                            categoryInfo = newCategoryInfo;
                        }

                        if (bzmcount > 0) {
                            // 确定工厂的价格体系
                            MlccPricesystemFactoryCategory factoryCategory = singleUtil.factoryCategory(gysid, categoryInfo.getId() + "", 2, 1);
                            if (factoryCategory != null) {
                                // 确定价格区间
                                MlccPricesystemFactoryRange range = singleUtil.getrange(factoryCategory.getId() + "", bzmcount);
                                if (range != null) {
                                    // 向派单工艺成本表添加记录
                                    MlccPaidanOrderGongyi paidanOrderGongyi = new MlccPaidanOrderGongyi();
                                    paidanOrderGongyi.setSysuserId(gysid).setOrderSn(orderSn).setOrderType(2).setCategoryId(gylx)
                                            .setCostPrice(range.getPrice()).setProductId(productInfo.getId())
                                            .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname()).setNum(bzmcount);
                                    int insert = paidanOrderGongyiMapper.insert(paidanOrderGongyi);
                                    if (insert < 1) {
                                        return 0;
                                    }
                                }
                            }
                        }

                        if (tdmcount > 0) {
                            // 确定工厂的价格体系
                            MlccPricesystemFactoryCategory factoryCategory = singleUtil.factoryCategory(gysid, categoryInfo.getId() + "", 1, 1);
                            if (factoryCategory != null) {
                                // 确定价格区间
                                MlccPricesystemFactoryRange range = singleUtil.getrange(factoryCategory.getId() + "", tdmcount);
                                if (range != null) {
                                    // 向派单工艺成本表添加记录
                                    MlccPaidanOrderGongyi paidanOrderGongyi = new MlccPaidanOrderGongyi();
                                    paidanOrderGongyi.setSysuserId(gysid).setOrderSn(orderSn).setOrderType(2)
                                            .setCategoryId(gylx).setCostPrice(range.getPrice()).setProductId(productInfo.getId())
                                            .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname()).setNum(tdmcount);
                                    int insert = paidanOrderGongyiMapper.insert(paidanOrderGongyi);
                                    if (insert < 1) {
                                        return 0;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return 1;
    }

    /**
     * 获取订单下的加价成本
     *
     * @param page    分页器
     * @param orderSn 订单编号
     */
    @Override
    public IPage<MlccPaidanOrderCost> getJiajiaCB(Page<MlccPaidanOrderCost> page, String orderSn) {
        QueryWrapper<MlccPaidanOrderCost> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        return paidanOrderCostMapper.selectPage(page, wrapper);
    }

    /**
     * 获取订单下的工艺成本
     *
     * @param page    分页器
     * @param orderSn 订单编号
     */
    @Override
    public IPage<MlccPaidanOrderGongyi> getGYCB(Page<MlccPaidanOrderGongyi> page, String orderSn) {
        QueryWrapper<MlccPaidanOrderGongyi> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        IPage<MlccPaidanOrderGongyi> iPage = paidanOrderGongyiMapper.selectPage(page, wrapper);
        List<MlccPaidanOrderGongyi> records = iPage.getRecords();
        if (records != null && records.size() > 0) {
            for (MlccPaidanOrderGongyi record : records) {
                MlccCategoryInfo categoryInfo = categoryInfoMapper.selectById(record.getCategoryId());
                if (categoryInfo != null) {
                    record.setGyname(categoryInfo.getCategoryName());
                }
            }
        }
        return iPage;
    }

    /**
     * 获取订单下的返修成本 (个订与团订通用)
     *
     * @param page    分页器
     * @param orderSn 订单编号
     */
    @Override
    public IPage<MlccPaidanOrderAfter> getFanxiuCB(Page<MlccPaidanOrderAfter> page, String orderSn) {
        QueryWrapper<MlccPaidanOrderAfter> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn).eq("status", 0);
        return paidanOrderAfterMapper.selectPage(page, wrapper);
    }

    /**
     * 返修的时候保存返修成本
     *
     * @param afterCode 售后订单编号
     * @param productID 产品ID
     * @param sizeID    返修尺寸id
     * @param orderSn   订单编号
     * @param sizename  尺寸名称
     * @param smallCode 小产品编号(如果是个订，直接传递null即可)
     */
    @Override
    public int saveFanxiuChengben(String afterCode, String productID, String sizeID, String orderSn, String sizename
            , String smallCode) {
        QueryWrapper<MlccSysuserOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn).eq("product_id", productID);
        MlccSysuserOrderInfo sysuserOrderInfo = paidanMapper.selectOne(wrapper);
        if (sysuserOrderInfo != null) {
            MlccProductInfo productInfo = productInfoMapper.selectById(productID);
            if (productInfo != null) {
                String plid = fabricUtil.getpingleiFromProduct(productInfo);
                if (plid != null) {
                    // 确定工厂的价格体系
                    MlccPricesystemFactoryCategory factoryCategory = singleUtil.factoryCategory(sysuserOrderInfo.getSysuserId(), plid, 0, 0);
                    if (factoryCategory != null) {
                        // 获取这个类型下供应商设置的返修成本
                        List<MlccPriceSystemFactoryRecord> records = singleUtil.listFactoryFanxiuRecord(plid, factoryCategory.getId() + "", sizeID);
                        if (records != null && records.size() > 0) {
                            for (MlccPriceSystemFactoryRecord record : records) {
                                // 向返修成本表添加记录（先添加一条没有启用的，等提交返修之后再启用这条记录）
                                MlccPaidanOrderAfter paidanafter = new MlccPaidanOrderAfter();
                                paidanafter.setSysuserId(sysuserOrderInfo.getSysuserId()).setOrderSn(orderSn).setOrderType(1)
                                        .setAfterCode(afterCode).setBodysizeId(sizeID).setCostPrice(record.getPrice()).setStatus(2)
                                        .setSizeName(sizename).setProductId(productID).setSmallProcode(smallCode);
                                int insert = paidanOrderAfterMapper.insert(paidanafter);
                                if (insert < 1) {
                                    return 0;
                                }
                            }
                        }
                    }
                }
            }
        }
        return 1;
    }

    /**
     * 启用返修的成本项（个订团订都可以使用）
     *
     * @param orderSn   订单编号
     * @param afterCode 售后订单编号
     */
    @Override
    public void takeonFanxiuChengben(String orderSn, String afterCode) {
        QueryWrapper<MlccPaidanOrderAfter> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn).eq("after_code", afterCode);
        List<MlccPaidanOrderAfter> orderAfters = paidanOrderAfterMapper.selectList(wrapper);
        if (orderAfters != null && orderAfters.size() > 0) {
            orderAfters.stream().forEach(after -> {
                after.setStatus(0);
                paidanOrderAfterMapper.updateById(after);
            });
        }
    }

    /**
     * 获取全部快递信息
     */
    @Override
    public List<MlccCourierInfo> getKuaidi() {
        return courierInfoMapper.selectList(null);
    }

    /**
     * 产品选择供应商
     *
     * @param proid 产品id
     * @param gysid 供应商id
     */
    @Override
    public int selectGYS(String proid, String gysid) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MlccProductInfo productInfo = productInfoMapper.selectById(proid);
        productInfo.setGysId(gysid).setUpdateBy(user.getRealname());
        return productInfoMapper.updateById(productInfo);
    }

    /**
     * 面料售后详情——后台发货的数据
     *
     * @param id 售后订单id
     */
    @Override
    public List<MlccTrackAfterOrder> fabricAdminFahuo(String id) {
        QueryWrapper<MlccTrackAfterOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("after_order_id", id).eq("status", 8).eq("type", 0);
        return trackAfterOrderMapper.selectList(wrapper);
    }

    /**
     * 面料售后详情——退款记录
     *
     * @param id 售后订单id
     */
    @Override
    public List<MlccTrackAfterOrder> fabrictuikuan(String id) {
        QueryWrapper<MlccTrackAfterOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("after_order_id", id).eq("status", 11).eq("type", 0);
        return trackAfterOrderMapper.selectList(wrapper);
    }

    /**
     * 完成订单
     *
     * @param orderSn 订单编号
     * @param type    0面；1个，2团
     */
    @Override
    public int orderOk(String orderSn, Integer type) {
        int result = 0;
        if (type == 1) {
            QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_sn", orderSn);
            MlccSingleOrderInfo singleOrderInfo = singleOrderInfoMapper.selectOne(wrapper);
            if (singleOrderInfo != null) {
                singleOrderInfo.setStatus(8);
                result = singleOrderInfoMapper.updateById(singleOrderInfo);
            }
        } else if (type == 2) {
            QueryWrapper<MlccTeamOrderInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_sn", orderSn);
            MlccTeamOrderInfo teamOrderInfo = teamOrderMapper.selectOne(wrapper);
            if (teamOrderInfo != null) {
                teamOrderInfo.setStatus(8);
                result = teamOrderMapper.updateById(teamOrderInfo);
            }
        }
        if (result > 0) {
            // 订单状态跟踪表添加记录
            MlccTrackingOrder trackingOrder = new MlccTrackingOrder();
            trackingOrder.setId(UUID.randomUUID().toString()).setOrderSn(orderSn).setOrderType(type).setThing("订单完成")
                    .setRemark("订单已完成")
                    .setOrderStatus(5);
            trackingOrderMapper.insert(trackingOrder);
            addKaipiao(orderSn, type);
        }
        return result;
    }

    /**
     * 完成售后订单
     *
     * @param id 售后订单id
     */
    @Override
    public int afterOK(String id) {
        MlccAfterSalesinfo afterSalesinfo = afterSalesinfoMapper.selectById(id);
        afterSalesinfo.setAfterstatus(3);
        int i = afterSalesinfoMapper.updateById(afterSalesinfo);
        if (i > 0) {
            // 如果这条订单名下的所有售后订单都完成了，那么改变订单的状态为售后完成
            orderAafterisOk(afterSalesinfo);
        }
        return i;
    }

    /**
     * 更新面料的售后价格
     *
     * @param price   价格
     * @param afterid 售后订单id
     */
    @Override
    public int updateFabricAfterPrice(String afterid, String price) {
        MlccAfterSalesinfo salesinfo = afterSalesinfoMapper.selectById(afterid);
        if (salesinfo != null) {
            salesinfo.setAfterPrice(price);
        }
        return afterSalesinfoMapper.updateById(salesinfo);
    }

    /**
     * 团体订单编辑批次删除装箱单
     *
     * @param boxid 装箱单id
     */
    @Override
    public int deleteBox(String boxid) {
        return batchPackingInfoMapper.deleteById(boxid);
    }

    /**
     * 团订获取重做的面料列表
     *
     * @param afterCode 售后订单编号
     */
    @Override
    public List<MlccFabricInfo> tramAfterFabriclIst(String afterCode) {
        // 存放最后的结果
        ArrayList<MlccFabricInfo> result = new ArrayList<>();
        // 查询本次售后所有重做的小产品
        QueryWrapper<MlccCustomerProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("after_code", afterCode).eq("is_after", 2);
        List<MlccCustomerProductInfo> list = smallProductMapper.selectList(wrapper);
        if (list != null && list.size() > 0) {
            for (MlccCustomerProductInfo info : list) {
                String fabricids = info.getFabricids();
                String[] idAndMishu = fabricids.split("/");
                MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(idAndMishu[0]);
                fabricInfo.setMishu(idAndMishu[1]).setCprice(info.getAfterFabricPrice());
                result.add(fabricInfo);
            }
        }
        // 将重复的面料合并
        if (result.size() > 0) {
            for (int i = 0; i < result.size(); i++) {
                for (int j = i + 1; j < result.size(); j++) {
                    // 面料相同，移除内层，米数和钱加到外层
                    if (result.get(i).getFabricCode().equals(result.get(j).getFabricCode())) {
                        // 合计米数
                        BigDecimal addMishu = new BigDecimal(Double.valueOf(result.get(i).getMishu())).add(new BigDecimal(Double.valueOf(result.get(j).getMishu())));
                        result.get(i).setMishu(addMishu.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                        // 合计价格
                        BigDecimal addPrice = result.get(i).getCprice().add(result.get(j).getCprice());
                        result.get(i).setCprice(addPrice);
                        // 移除j
                        result.remove(j);
                    }
                }
            }
        }
        return result;
    }

    /**
     * 小产品详情
     *
     * @param id 小产品id
     */
    @Override
    public MlccCustomerProductInfo smallProDetail(String id) {
        return smallProductMapper.selectById(id);
    }


    /*-------------------------工具方法---------------------------*/

    /**
     * 如果这条订单名下的所有售后订单都完成了，那么改变订单的状态为售后完成
     *
     * @param afterSalesinfo 售后订单对象
     */
    public void orderAafterisOk(MlccAfterSalesinfo afterSalesinfo) {
        // 统计原订单的售后订单还没有完成的数量
        QueryWrapper<MlccAfterSalesinfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", afterSalesinfo.getOrderSn()).eq("status", 0).ne("afterstatus", 3);
        int count = afterSalesinfoMapper.selectCount(wrapper);
        if (count == 0) {
            // 如果售后订单全部完成了，把订单状态改为售后完成状态
            if (afterSalesinfo.getOrdertype() == 0) {
                // 面料订单
                MlccFabricOrderinfo orderinfo = fabricOrderinfoMapper.selectById(afterSalesinfo.getOrderId());
                orderinfo.setStatus(11);
                fabricOrderinfoMapper.updateById(orderinfo);
            } else if (afterSalesinfo.getOrdertype() == 1) {
                // 个订订单
                MlccSingleOrderInfo orderInfo = singleOrderInfoMapper.selectById(afterSalesinfo.getOrderId());
                orderInfo.setStatus(12);
                singleOrderInfoMapper.updateById(orderInfo);
            } else if (afterSalesinfo.getOrdertype() == 2) {
                // 团订订单
                MlccTeamOrderInfo orderInfo = teamOrderMapper.selectById(afterSalesinfo.getOrderId());
                orderInfo.setStatus(12);
                teamOrderMapper.updateById(orderInfo);
            }
        }
    }

    /**
     * 个订添加派单记录
     *
     * @param productInfo 产品对象
     * @param orderSn     订单编号
     */
    public int addPaidan(MlccProductInfo productInfo, String orderSn) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccSingleOrderInfo orderInfo = singleOrderInfoMapper.selectOne(wrapper);
        MlccSysuserOrderInfo info = new MlccSysuserOrderInfo();
        info.setSysuserId(productInfo.getGysId()).setProductId(productInfo.getId())
                .setOrderId(orderInfo.getId() + "").setOrderSn(orderSn).setOrderType(1)
                .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname());
        return sysuserOrderInfoMapper.insert(info);
    }

    /**
     * 个订产品选择供应商，插入成本列表数据（个订）   新
     *
     * @param orderSn     订单编号
     * @param productInfo 产品对象
     * @param gysid       供应商id
     */
    public int savePaidanChengbenNew(String orderSn, MlccProductInfo productInfo, String gysid) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取当前产品的品类ID
        String PLID = fabricUtil.getpingleiFromProduct(productInfo);
        if (PLID != null) {
            // 确定工厂的价格体系
            MlccPricesystemFactoryCategory factoryCategory = singleUtil.factoryCategory(gysid, PLID, 0, 0);
            if (factoryCategory != null) {
                // 获取这个类型下供应商设置的所有成本
                List<MlccPriceSystemFactoryRecord> records = singleUtil.listFactoryRecord(PLID, factoryCategory.getId() + "");
                System.out.println("查到的成本项：" + records);
                if (records != null && records.size() > 0) {
                    for (MlccPriceSystemFactoryRecord record : records) {
                        MlccPaidanOrderCost paidanOrderCost = new MlccPaidanOrderCost();
                        paidanOrderCost.setSysuserId(gysid).setOrderSn(orderSn).setOrderType(1).setCostItem(record.getCostItem())
                                .setCostName(record.getCostName()).setCostId(record.getCostId()).setPrice(record.getPrice())
                                .setProductId(productInfo.getId())
                                .setType(record.getType()).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname());
                        int insert = paidanOrderCostMapper.insert(paidanOrderCost);
                        if (insert < 1) {
                            return 0;
                        }
                    }
                }
            }
        }
        return 1;
    }

    /**
     * 供应商派单之后，插入工艺成本数据（个订）新
     *
     * @param orderSn
     * @param productInfo
     * @param gysid
     * @return
     */
    public int savePaidanGYNew(String orderSn, MlccProductInfo productInfo, String gysid) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取产品的工艺类型ID
        String gylx = fabricUtil.getGYLXFromProduct(productInfo);
        String plid = fabricUtil.getpingleiFromProduct(productInfo);
        if (gylx != null) {
            // 这是原来的工艺类型对象，没有设置折扣
            MlccCategoryInfo categoryInfo = categoryInfoMapper.selectById(gylx);
            /*注意：需要重新定位到真正的工艺id，此时查到的是前端展示，与设置折扣的工艺不是同一个，但是编号相同*/
            QueryWrapper<MlccCategoryInfo> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("category_code", categoryInfo.getCategoryCode()).eq("topid", plid)
                    .eq("is_type", 4).eq("status", 0);
            // 这是查询到了设置了折扣的工艺
            MlccCategoryInfo newCategoryInfo = categoryInfoMapper.selectOne(wrapper1);
            if (newCategoryInfo != null) {
                categoryInfo = newCategoryInfo;
            }

            // 确定工厂的价格体系
            MlccPricesystemFactoryCategory factoryCategory = singleUtil.factoryCategory(gysid, categoryInfo.getId() + "", 0, 1);
            if (factoryCategory != null) {
                // 确定价格区间
                MlccPricesystemFactoryRange range = singleUtil.getrange(factoryCategory.getId() + "", 1);
                if (range != null) {
                    // 向派单工艺成本表添加记录
                    MlccPaidanOrderGongyi paidanOrderGongyi = new MlccPaidanOrderGongyi();
                    paidanOrderGongyi.setSysuserId(gysid).setOrderSn(orderSn).setOrderType(1).setCategoryId(gylx).setCostPrice(range.getPrice())
                            .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname()).setProductId(productInfo.getId());
                    int insert = paidanOrderGongyiMapper.insert(paidanOrderGongyi);
                    if (insert < 1) {
                        return 0;
                    }
                }
            }
        }
        return 1;
    }

    /**
     * 未支付面料订单调价
     *
     * @param user          当前登录账号
     * @param trackingOrder 订单跟踪
     * @param orderSn       订单编号
     * @param price         调价金额
     * @param remark        调价备注
     */
    public int fabricPricing(LoginUser user, MlccTrackingOrder trackingOrder, String orderSn, String price, String remark) {
        // 面料订单的调价
        QueryWrapper<MlccFabricOrderinfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn).eq("status", 0);
        MlccFabricOrderinfo orderinfo = fabricOrderinfoMapper.selectOne(wrapper);
        MlccUserInfo userDetail = userInfoMapper.selectById(orderinfo.getUserId());

        if (orderinfo == null) return -1; // 这个订单不存在或者已经支付
        String pririPrice = orderinfo.getOrderMoney();// 调价前金额
        // 更新订单金额
        orderinfo.setOrderMoney(price).setUpdateBy(user.getRealname()).setPriorPrice(new BigDecimal(new Double(pririPrice)));
        if (orderinfo.getFirstPrice() == null) {
            orderinfo.setFirstPrice(new BigDecimal(new Double(pririPrice)));
        }
        int updateResult = fabricOrderinfoMapper.updateById(orderinfo);
        if (updateResult > 0) {
            // 2、向业务流水表添加数据，这里要进行判断，确保一条订单只有一条流水数据
            QueryWrapper<MlccBusinessWaterInfo> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("order_id", orderinfo.getId()).eq("type", 0);
            MlccBusinessWaterInfo businessWaterInfo = businessWaterInfoMapper.selectOne(wrapper1);
            if (businessWaterInfo == null) {
                MlccBusinessWaterInfo waterInfo = new MlccBusinessWaterInfo();
                waterInfo.setOrderId(orderinfo.getId() + "").setType(0).setUserId(userDetail.getId() + "")
                        .setCostMoney(orderinfo.getOrderMoney()).setYewuInstructions("异常业务").setYewuDeatil("面料订单调价")
                        .setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername());
                businessWaterInfoMapper.insert(waterInfo);
            } else {
                businessWaterInfo.setStatus(2).setUpdateBy(userDetail.getUsername());
                businessWaterInfoMapper.updateById(businessWaterInfo);
            }
            // 3、往订单跟踪表添加数据
            trackingOrder.setOrderSn(orderSn).setOrderType(0).setThing("面料订单调价")
                    .setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername()).setRemark(remark);
            trackingOrderMapper.insert(trackingOrder);
            // 4、往异常订单表添加记录
            MlccErrorOrder errorOrder = new MlccErrorOrder();
            errorOrder.setId(UUID.randomUUID().toString().substring(0, 12)).setErrorName("面料订单调价")
                    .setOrderSn(orderSn).setOrderType(0).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname())
                    .setSysOrgCode(user.getOrgCode());
            errorOrderMapper.insert(errorOrder);
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 未支付个订订单调价
     *
     * @param user
     * @param trackingOrder
     * @param orderSn
     * @param price
     * @return
     */
    public int singleOrderPricing(LoginUser user, MlccTrackingOrder trackingOrder, String orderSn, String price, String remark) {
        // 个订订单的调价
        QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn).eq("status", 11);
        MlccSingleOrderInfo orderinfo = singleOrderInfoMapper.selectOne(wrapper);
        MlccUserInfo userDetail = userInfoMapper.selectById(orderinfo.getUserId());

        if (orderinfo == null) return -1; // 这个订单不存在或者已经支付
        String pririPrice = orderinfo.getOrderMoney();// 调价前金额
        orderinfo.setPricing(price).setUpdateBy(user.getRealname()).setOrderMoney(price).setPriorPrice(new BigDecimal(new Double(pririPrice)));
        if (orderinfo.getFirstPrice() == null) {
            orderinfo.setFirstPrice(new BigDecimal(new Double(pririPrice)));
        }
        int updateResult = singleOrderInfoMapper.updateById(orderinfo);
        if (updateResult > 0) {
            // 2、向业务流水表添加数据，这里要进行判断，确保一条订单只有一条流水数据
            QueryWrapper<MlccBusinessWaterInfo> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("order_id", orderinfo.getId()).eq("type", 1);
            MlccBusinessWaterInfo businessWaterInfo = businessWaterInfoMapper.selectOne(wrapper1);
            if (businessWaterInfo == null) {
                MlccBusinessWaterInfo waterInfo = new MlccBusinessWaterInfo();
                waterInfo.setOrderId(orderinfo.getId() + "").setType(1).setUserId(userDetail.getId() + "")
                        .setCostMoney(orderinfo.getPricing()).setYewuInstructions("异常业务").setYewuDeatil("个定订单调价")
                        .setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername());
                businessWaterInfoMapper.insert(waterInfo);
            } else {
                businessWaterInfo.setStatus(2).setUpdateBy(userDetail.getUsername());
                businessWaterInfoMapper.updateById(businessWaterInfo);
            }
            // 3、往订单跟踪表添加数据
            trackingOrder.setOrderSn(orderSn).setOrderType(1).setRemark(remark).setThing("个定订单调价")
                    .setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername());
            trackingOrderMapper.insert(trackingOrder);
            // 4、往异常订单表添加记录
            MlccErrorOrder errorOrder = new MlccErrorOrder();
            errorOrder.setId(UUID.randomUUID().toString().substring(0, 12)).setErrorName("个定订单调价")
                    .setOrderSn(orderSn).setOrderType(1).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname())
                    .setSysOrgCode(user.getOrgCode());
            errorOrderMapper.insert(errorOrder);
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 团订订单调价
     *
     * @param user
     * @param trackingOrder
     * @param orderSn
     * @param price
     * @return
     */
    public int teamOrderPricing(LoginUser user, MlccTrackingOrder trackingOrder, String orderSn, String price, String remark) {
        // 个订订单的调价
        QueryWrapper<MlccTeamOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn).eq("status", 11);
        MlccTeamOrderInfo orderinfo = teamOrderMapper.selectOne(wrapper);
        MlccUserInfo userDetail = userInfoMapper.selectById(orderinfo.getUserId());

        if (orderinfo == null) return -1; // 这个订单不存在或者已经支付
        String pririPrice = orderinfo.getOrderMoney();// 调价前金额
        orderinfo.setOrderMoney(price).setPricing(price).setUpdateBy(user.getRealname()).setPriorPrice(new BigDecimal(new Double(pririPrice)));
        if (orderinfo.getFirstPrice() == null) {
            orderinfo.setFirstPrice(new BigDecimal(new Double(pririPrice)));
        }
        int updateResult = teamOrderMapper.updateById(orderinfo);
        if (updateResult > 0) {
            // 2、向业务流水表添加数据，这里要进行判断，确保一条订单只有一条流水数据
            QueryWrapper<MlccBusinessWaterInfo> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("order_id", orderinfo.getId()).eq("type", 2);
            MlccBusinessWaterInfo businessWaterInfo = businessWaterInfoMapper.selectOne(wrapper1);
            if (businessWaterInfo == null) {
                MlccBusinessWaterInfo waterInfo = new MlccBusinessWaterInfo();
                waterInfo.setOrderId(orderinfo.getId() + "").setType(2).setUserId(userDetail.getId() + "")
                        .setCostMoney(orderinfo.getPricing()).setYewuInstructions("异常业务").setYewuDeatil("团体订单调价")
                        .setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername());
                businessWaterInfoMapper.insert(waterInfo);
            } else {
                businessWaterInfo.setStatus(0).setUpdateBy(userDetail.getUsername());
                businessWaterInfoMapper.updateById(businessWaterInfo);
            }
            // 3、往订单跟踪表添加数据
            trackingOrder.setOrderSn(orderSn).setOrderType(2).setRemark(remark).setThing("团体订单调价")
                    .setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername());
            trackingOrderMapper.insert(trackingOrder);
            // 4、往异常订单表添加记录
            MlccErrorOrder errorOrder = new MlccErrorOrder();
            errorOrder.setId(UUID.randomUUID().toString().substring(0, 12)).setErrorName("团体订单调价")
                    .setOrderSn(orderSn).setOrderType(2).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname())
                    .setSysOrgCode(user.getOrgCode());
            errorOrderMapper.insert(errorOrder);
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 往订单跟踪表添加数据
     *
     * @param orderSn     订单编号
     * @param orderType   订单类型
     * @param remark      备注
     * @param username    更新人
     * @param orderStatus 0未支付，1已支付，2申请售后，3已接单，4已发货，5已完成，6备库
     * @param thing       订单事件
     */
    public void addtrackingOrder(String orderSn, int orderType, String remark, String username, Integer orderStatus, String thing) {
        MlccTrackingOrder trackingOrder = new MlccTrackingOrder();
        trackingOrder.setOrderSn(orderSn).setOrderType(orderType).setRemark(remark)
                .setThing(thing)
                .setCreateBy(username).setUpdateBy(username).setOrderStatus(orderStatus);
        trackingOrderMapper.insert(trackingOrder);
    }

    /*
     * 驳回退钱  （废弃）
     *
     * @param userid 用户id
     * @param Money  订单金额
     * @param type   支付类型
     */
    /*
    public void bohuiMoney(String userid, String Money, Integer type) {
        // 退钱
        MlccUserInfo userInfo = userInfoMapper.selectById(userid);
        // 订单余额
        BigDecimal orderMoney = new BigDecimal(Double.valueOf(Money));
        if (userInfo != null) {
            if (type == 4) {
                // 退款至余额
                BigDecimal yu = new BigDecimal(Double.valueOf(userInfo.getAccountBalance()));
                BigDecimal add = yu.add(orderMoney);
                userInfo.setAccountBalance(add.setScale(2, BigDecimal.ROUND_FLOOR).toString());
                userInfoMapper.updateById(userInfo);
            }
            if (type == 5) {
                // 退款至月结
                BigDecimal yue = new BigDecimal(Double.valueOf(userInfo.getMonthLines()));
                BigDecimal add = yue.add(orderMoney);
                userInfo.setRemainingLimit(add.setScale(2, BigDecimal.ROUND_FLOOR));
                userInfoMapper.updateById(userInfo);
            }
        }
    }*/

    /**
     * 驳回订单的退款操作
     *
     * @param orderSn   订单id
     * @param orderType 订单类型 0面料，1个订，2团订
     * @param userid    支付的账号id
     */
    public void bohuiMoneyBack(String orderid, Integer orderType, String userid) {
        // 创建订单账号的基本信息
        MlccUserInfo userInfo = userInfoMapper.selectById(userid);
        // 查询公司账号
        QueryWrapper<MlccCompanyInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("company_code", userInfo.getCompanyOrgcode());
        MlccCompanyInfo companyInfo = companyInfoMapper.selectOne(wrapper);
        // 根据公司数据找到公司账号
        MlccUserInfo companyUser = userInfoMapper.selectById(companyInfo.getUserId());
        if (companyUser == null) {
            throw new RuntimeException("公司账号不存在");
        } else {
            userInfo = companyUser;
        }
        if (orderType == 0) {
            // 如果是面料订单
            MlccFabricOrderinfo mlccFabricOrderinfo = fabricOrderinfoMapper.selectById(orderid);
            // 计算恢复的余额
            BigDecimal add = new BigDecimal(Double.valueOf(userInfo.getAccountBalance())).add(mlccFabricOrderinfo.getBalancePay());
            // 把支付的钱退回去
            userInfo.setDeductionLimit(userInfo.getDeductionLimit().add(mlccFabricOrderinfo.getDeductionPay()))
                    .setRemainingLimit(userInfo.getRemainingLimit().add(mlccFabricOrderinfo.getMonthPay()))
                    .setAccountBalance(add.toString());
        } else if (orderType == 1) {
            // 如果是个订
            MlccSingleOrderInfo singleOrderInfo = singleOrderInfoMapper.selectById(orderid);
            // 计算恢复的余额
            BigDecimal add = new BigDecimal(Double.valueOf(userInfo.getAccountBalance())).add(singleOrderInfo.getBalancePay());
            // 把支付的钱退回去
            userInfo.setDeductionLimit(userInfo.getDeductionLimit().add(singleOrderInfo.getDeductionPay()))
                    .setRemainingLimit(userInfo.getRemainingLimit().add(singleOrderInfo.getMonthPay()))
                    .setAccountBalance(add.toString());
        } else if (orderType == 2) {
            // 如果是团订
            MlccTeamOrderInfo teamOrderInfo = teamOrderMapper.selectById(orderid);
            // 计算恢复的余额
            BigDecimal add = new BigDecimal(Double.valueOf(userInfo.getAccountBalance())).add(teamOrderInfo.getBalancePay());
            // 把支付的钱退回去
            userInfo.setDeductionLimit(userInfo.getDeductionLimit().add(teamOrderInfo.getDeductionPay()))
                    .setRemainingLimit(userInfo.getRemainingLimit().add(teamOrderInfo.getMonthPay()))
                    .setAccountBalance(add.toString());
        }
        userInfoMapper.updateById(userInfo);
    }

    /**
     * 驳回售后退钱的方法(个订团订通用)
     *
     * @param afterOrderId 售后订单id
     * @param userid       付款账户id
     */
    public void rejectedAfter(String afterOrderId, String userid) {
        // 支付账号基本信息
        MlccUserInfo userInfo = userInfoMapper.selectById(userid);
        // 查询公司账号
        QueryWrapper<MlccCompanyInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("company_code", userInfo.getCompanyOrgcode());
        MlccCompanyInfo companyInfo = companyInfoMapper.selectOne(wrapper);
        // 根据公司数据找到公司账号
        MlccUserInfo companyUser = userInfoMapper.selectById(companyInfo.getUserId());
        if (companyUser == null) {
            throw new RuntimeException("公司账号不存在");
        } else {
            userInfo = companyUser;
        }

        // 售后订单基本信息
        MlccAfterSalesinfo afterSalesinfo = afterSalesinfoMapper.selectById(afterOrderId);
        // 计算恢复的余额
        BigDecimal add = new BigDecimal(Double.valueOf(userInfo.getAccountBalance())).add(afterSalesinfo.getBalancePay()).setScale(2, BigDecimal.ROUND_HALF_UP);
        // 把支付的钱退回去
        userInfo.setDeductionLimit(userInfo.getDeductionLimit().add(afterSalesinfo.getDeductionPay()))
                .setRemainingLimit(userInfo.getRemainingLimit().add(afterSalesinfo.getMonthPay()))
                .setAccountBalance(add.toString());
        userInfoMapper.updateById(userInfo);
    }

    /**
     * 完成订单之后，在
     *
     * @param orderSn 订单编号
     * @param type    订单类型 0面 1个 2团
     */
    void addKaipiao(String orderSn, Integer type) {
        MlccUserInfo user = null;
        String orderMoney = "";
        if (type == 0) {
            QueryWrapper<MlccFabricOrderinfo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_sn", orderSn);
            MlccFabricOrderinfo one = fabricOrderinfoMapper.selectOne(wrapper);
            if (one != null) {
                orderMoney = one.getOrderMoney();
                user = userInfoMapper.selectById(one.getUserId());
            }
        } else if (type == 1) {
            QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_sn", orderSn);
            MlccSingleOrderInfo one = singleOrderInfoMapper.selectOne(wrapper);
            if (one != null) {
                orderMoney = one.getOrderMoney();
                user = userInfoMapper.selectById(one.getUserId());
            }
        } else if (type == 2) {
            QueryWrapper<MlccTeamOrderInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_sn", orderSn);
            MlccTeamOrderInfo one = teamOrderMapper.selectOne(wrapper);
            if (one != null) {
                orderMoney = one.getOrderMoney();
                user = userInfoMapper.selectById(one.getUserId());
            }
        }
        // 此时拿到了user
        if (user != null) {
            // 查询公司账号
            QueryWrapper<MlccCompanyInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("company_code", user.getCompanyOrgcode());
            MlccCompanyInfo companyInfo = companyInfoMapper.selectOne(wrapper);
            // 根据公司数据找到公司账号
            MlccUserInfo companyUser = userInfoMapper.selectById(companyInfo.getUserId());
            if (companyUser == null) {
                throw new RuntimeException("公司账号不存在");
            } else {
                user = companyUser;
            }
            // 此时拿到了真正的公司账号
            BigDecimal add = user.getNoenterMoney().add(new BigDecimal(Double.valueOf(orderMoney))).setScale(2, BigDecimal.ROUND_HALF_UP);
            user.setNoenterMoney(add);
            userInfoMapper.updateById(user);
        }
    }
}
